Custom Style Formats for WordPress WYSIWYG Editor

Sometimes you need to make some helpers for content editors in the WYSIWYG editor rather than trying to teach a client how to write in html attributes in the code view, which is obviously prone to error and user frustration. You can create custom shortcodes for more complex formatting, but if you just need to do something simple, like adding a class to a link for example, you can make use of the TinyMCE Custom Styles API.

As an example, I had a site that had two distinct button styles, and we needed clients to be able to insert these into the editor. Using the custom styles api, I added options to the “Formats” drop down menu in the editor, with formats that are only available when a link is selected.

Code used to achieve this:

// Callback function to insert 'styleselect' into the $buttons array
function aceify_mce_buttons( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}
// Register our callback to the appropriate filter
// mce_buttons = The primary toolbar (always visible)
// mce_buttons_2 = The advanced toolbar (can be toggled on/off by user)
add_filter('mce_buttons', 'aceify_mce_buttons');

// Callback function to filter the MCE settings
function aceify_mce_before_init_insert_formats( $init_array ) { 
    // Define the style_formats array
    $style_formats = array( 
        // Each array child is a format with it's own settings
        array( 
            'title' => 'Blue Button', 
            'selector' => 'a', 
            'classes' => 'blue-button' 
        ),
        array( 
            'title' => 'Grey Button', 
            'selector' => 'a', 
            'classes' => 'button' 
        )
    ); 
    // Insert the array, JSON ENCODED, into 'style_formats'
    $init_array['style_formats'] = json_encode( $style_formats ); 

    return $init_array; 
} 
// Attach callback to 'tiny_mce_before_init' 
add_filter( 'tiny_mce_before_init', 'aceify_mce_before_init_insert_formats' );