WordPress: Assign custom CSS classes with the Visual Editor (TinyMCE)

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.

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.

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