As a WordPress theme developer, it’s very useful to be able to define CSS classes in a theme’s stylesheet, then allow them to be assigned to elements by the user with the Visual editor. Classic examples would be special classes to style links, lists and images.
For anyone comfortable with editing code, it’s easy enough to switch to HTML mode and add the class attribute manually to the desired element. But for most people, it’s far easier to select the text or image, then choose the desired style from a dropdown.
To set up this capability we need to:
- hook into the tiny_mce_before_init filter
- define the list of classes we wish to appear in the dropdown
- activate the “Styles” dropdown in the editor
The format for the custom class list is {label}={class-name} seperated by semi-colons,
e.g.
“Special Style 1=special-1;Special Style 2=special-2;Special Style 3=special-3”
Using this example list of classes, the code which can go in your functions.php file is as follows:
add_filter('tiny_mce_before_init', 'add_custom_classes'); function add_custom_classes($arr_options) { $arr_options['theme_advanced_styles'] = "Special Style 1=special-1;Special Style 2=special-2;Special Style 3=special-3"; $arr_options['theme_advanced_buttons2_add_before'] = "styleselect"; return $arr_options; } |
Note: Prior to WordPress 3.1, the “Insert/edit link” dialog included a “class” drop down, which was populated by the same theme_advanced_styles list we have used here. In version 3.1 this drop down was removed by the core dev team. The technique described in this post is one way to work around this update to the WordPress admin.
http://pastie.org/pastes/1975133/text
Hi Trisha – thanks for visiting!
For text, the class gets applied via a new span around the selected text.. For images and links, the class gets applied directly to the element..
You could create a button to apply a class but you’d also need to code that functionality from scratch. By using the Styles dropdown the functionality already exists.
Hope that helps 🙂
Awesome! Just what I need right now! 🙂 It even recognizes the old manually entered text! Very much thank you!
Hi again. I was just looking this up again for a client’s site, when I came across ‘method 2’ here: http://alisothegeek.com/2011/05/tinymce-styles-dropdown-wordpress-visual-editor/
Thought you might find it interesting.
Thanks a lot for this, very useful! And a lot cleaner than using extra plugins, when all you need is a styles drop-down.
This is bloody brilliant, and exactly what I was looking for. Thank you so much.