Add CSS Class to Link in TinyMCE editor

The question:

In searching for a solution, I’ve come across the plugin to enable a dropdown of CSS styles already present within a stylesheet. What I want is to allow the editor to add CSS Classes from a textbox. So if you consider this image:

enter image description here

What I’m ideally looking for is a way to get another textbox in there below Title called Class. The freedom to type in a CSS class is needed for other functionality within the site. Any ideas on how I can achieve this?

Many thanks!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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
            '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.

Method 2

I was able to solve this by adding the WP Edit plugin to my site. It has an Advanced Link button, that allows me (or an editor) to manually type in a classname.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment