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!

2 s
2

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.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *