Add CSS Class to Link in TinyMCE editor

One option is to add a class to the Styleselect menu in MCE. Adapted from the “TinyMCE Custom Styles” Codex page you first need to add the style select to the editor:

// Callback function to insert 'styleselect' into the $buttons array
function my_mce_buttons_2( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}
// Register our callback to the appropriate filter
add_filter('mce_buttons_2', 'my_mce_buttons_2');

That will add the new drop down to the editor. Then you create your custom styles:

// Callback function to filter the MCE settings
function my_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' => 'My Link Custom Class',  
            'selector' => 'a',  
            'classes' => 'my-custom-link-class'             
        )
    );  
    // 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', 'my_mce_before_init_insert_formats' );

As of WordPress 3.9 which included an upgrade to TinyMCE 4.0, the style select is much more robust and includes that selector rule that means you can define styles that only can be applied to links. It’s pretty nice.

This solution means you can pre-define the classes you need and ensure there are never typos or other problems.

As the Codex notes, this is best combined with a good editor-style.css file that will apply your styles directly in the editor.

Leave a Comment