Try Tuts+ Premium, Get Cash Back!
Adding Custom Styles in WordPress TinyMCE Editor

Adding Custom Styles in WordPress TinyMCE Editor

Tutorial Details
  • Program: WordPress
  • Difficulty: Medium
  • Estimated Completion Time: 15 minutes
  • Prerequisites: Basic knowledge of WordPress coding

If you are creating a WordPress theme to power a website that will be updated by individuals without any knowledge of HTML, you can add custom styles to the visual TinyMCE editor and ensure that elements are properly formatted.


As a web designer or developer, you can create custom styles for various elements in the content of a WordPress website. These styles can be easily added by editing the HTML. What if the end-user or author of the website is not familiar with HTML? What if the author forgot which element was required for the desired style?

Adding custom styles to the WYSIWYG editor (TinyMCE) interface will allow the user to style an element with appropriate custom CSS without having to remember any code. Simply select the element or text and apply the relevant format using the style dropdown menu available in the visual editor. It is fairly easy to add a ‘Styles’ dropdown to the ‘Kitchen Sink’ in WordPress. Adding custom styles to the visual editor in WordPress is perfect for adding elements such as warning messages, buttons and testimonials.

Note: Below we’ll be creating variations of some open source code called TinyMCE Kit from the WordPress plugin repository which is released under the GPL v.2 license.


Quick Fix

Adding custom styles to the TinyMCE editor in WordPress is a fairly easy process. Below is a simple plug-in that adds custom styles mentioned in an array class to the visual editor in the ‘Styles’ drop-down. The CSS styles are placed in a file in the plug-in folder. This CSS stylesheet is called in the visual editor as well as the front-end of the website.

The code has been commented to make it easy to understand. In the first part, we make use of a TinyMCE function to add the custom stylesheet to the visual editor so that all styles are visible there. The next part adds the ‘Styles’ drop-down, which is populated in the subsequent step. The ‘Styles’ dropdown ('styleselect') is added to the second row of buttons (theme_advanced_buttons2_add) at the beginning of the row (_before). This drop-down is then populated with custom styles, which are added through the $classes array instead of writing directly in the format prescribed in the TinyMCE documentation. In the final part, the custom stylesheet is added to the front-end using the wp_enqueue_scripts function.

<?php
/*
Plugin Name: Custom Quick Styles
Plugin URI: http://www.speckygeek.com
Description: Add custom styles in your posts and pages content using TinyMCE WYSIWYG editor. The plugin adds a Styles dropdown menu in the visual post editor.
Based on TinyMCE Kit plug-in for WordPress

http://plugins.svn.wordpress.org/tinymce-advanced/branches/tinymce-kit/tinymce-kit.php

*/
/**
 * Apply styles to the visual editor
 */  
add_filter('mce_css', 'tuts_mcekit_editor_style');
function tuts_mcekit_editor_style($url) {

    if ( !empty($url) )
        $url .= ',';

    // Retrieves the plugin directory URL and adds editor stylesheet
    // Change the path here if using different directories
    $url .= trailingslashit( plugin_dir_url(__FILE__) ) . '/editor-styles.css';

    return $url;
}

/**
 * Add "Styles" drop-down
 */  
function tuts_mcekit_editor_buttons($buttons) {
    array_unshift($buttons, 'styleselect');
    return $buttons;
}

add_filter('mce_buttons_2', 'tuts_mcekit_editor_buttons');

/**
 * Add "Styles" drop-down content or classes
 */  
function tuts_mcekit_editor_settings($settings) {
    if (!empty($settings['theme_advanced_styles']))
        $settings['theme_advanced_styles'] .= ';';    
    else
        $settings['theme_advanced_styles'] = '';

    /**
     * Add styles in $classes array.
     * The format for this setting is "Name to display=class-name;".
     * More info: http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/theme_advanced_styles
     *
     * To be allow translation of the class names, these can be set in a PHP array (to keep them
     * readable) and then converted to TinyMCE's format. You will need to replace 'textdomain' with
     * your theme's textdomain.
     */
    $classes = array(
        __('Warning','textdomain') => 'warning',
        __('Notice','textdomain') => 'notice',
        __('Download','textdomain') => 'download',
        __('Testimonial','textdomain') => 'testimonial box',
    );

    $class_settings = '';
    foreach ( $classes as $name => $value )
        $class_settings .= "{$name}={$value};";

    $settings['theme_advanced_styles'] .= trim($class_settings, '; ');
    return $settings;
} 

add_filter('tiny_mce_before_init', 'tuts_mcekit_editor_settings');

/*
 * Add custom stylesheet to the website front-end with hook 'wp_enqueue_scripts'
 * Enqueue the custom stylesheet in the front-end
 */
add_action('wp_enqueue_scripts', 'tuts_mcekit_editor_enqueue');
function tuts_mcekit_editor_enqueue() {
  $StyleUrl = plugin_dir_url(__FILE__).'editor-styles.css';
  wp_enqueue_style( 'myCustomStyles', $StyleUrl );
}
?>

Elaborate Styling

The above solution for adding custom styles to the WordPress visual editor is quick, but it has some limitations. The above code will not limit a style to a specific HTML element. It will also not apply a class to an existing block element.

We can remove these limitations and make our custom styles drop-down more powerful by putting the styles in arrays using TinyMCE syntax to define the formats. After this, we encode the styles as JSON and then add them to the TinyMCE settings. The rest of the plug-in codes remain unchanged.

In TinyMCE, each format has a set of parameters that you can specify. (Source: TinyMCE – formats)

  • inline – Name of the inline element to produce for example “span”. The current text selection will be wrapped in this inline element.
  • block – Name of the block element to produce for example “h1″. Existing block elements within the selection gets replaced with the new block element.
  • selector – CSS 3 selector pattern to find elements within the selection by. This can be used to apply classes to specific elements or complex things like odd rows in a table.
  • classes – Space separated list of classes to apply the the selected elements or the new inline/block element.
  • styles – Name/value object with CSS style items to apply such as color etc.
  • attributes – Name/value object with attributes to apply to the selected elements or the new inline/block element.
  • exact – Disables the merge similar styles feature when used. This is needed for some CSS inheritance issues such as text-decoration for underline/strikethough.
  • wrapper – State that tells that the current format is a container format for block elements. For example a div wrapper or blockquote.

Here is the modified plug-in for adding custom styles to the WordPress visual editor.

<?php
/*
Plugin Name: Custom Styles
Plugin URI: http://www.speckygeek.com
Description: Add custom styles in your posts and pages content using TinyMCE WYSIWYG editor. The plugin adds a Styles dropdown menu in the visual post editor.
Based on TinyMCE Kit plug-in for WordPress

http://plugins.svn.wordpress.org/tinymce-advanced/branches/tinymce-kit/tinymce-kit.php

*/
/**
 * Apply styles to the visual editor
 */  
add_filter('mce_css', 'tuts_mcekit_editor_style');
function tuts_mcekit_editor_style($url) {

    if ( !empty($url) )
        $url .= ',';

    // Retrieves the plugin directory URL
    // Change the path here if using different directories
    $url .= trailingslashit( plugin_dir_url(__FILE__) ) . '/editor-styles.css';

    return $url;
}

/**
 * Add "Styles" drop-down
 */ 
add_filter( 'mce_buttons_2', 'tuts_mce_editor_buttons' );

function tuts_mce_editor_buttons( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}

/**
 * Add styles/classes to the "Styles" drop-down
 */ 
add_filter( 'tiny_mce_before_init', 'tuts_mce_before_init' );

function tuts_mce_before_init( $settings ) {

    $style_formats = array(
        array(
            'title' => 'Download Link',
            'selector' => 'a',
            'classes' => 'download'
            ),
        array(
            'title' => 'Testimonial',
            'selector' => 'p',
            'classes' => 'testimonial',
        ),
        array(
            'title' => 'Warning Box',
            'block' => 'div',
            'classes' => 'warning box',
            'wrapper' => true
        ),
        array(
            'title' => 'Red Uppercase Text',
            'inline' => 'span',
            'styles' => array(
                'color' => '#ff0000',
                'fontWeight' => 'bold',
                'textTransform' => 'uppercase'
            )
        )
    );

    $settings['style_formats'] = json_encode( $style_formats );

    return $settings;

}

/* Learn TinyMCE style format options at http://www.tinymce.com/wiki.php/Configuration:formats */

/*
 * Add custom stylesheet to the website front-end with hook 'wp_enqueue_scripts'
 */
add_action('wp_enqueue_scripts', 'tuts_mcekit_editor_enqueue');

/*
 * Enqueue stylesheet, if it exists.
 */
function tuts_mcekit_editor_enqueue() {
  $StyleUrl = plugin_dir_url(__FILE__).'editor-styles.css'; // Customstyle.css is relative to the current file
  wp_enqueue_style( 'myCustomStyles', $StyleUrl );
}
?>

So you have an plug-in to add custom styles in the WordPress visual editor. To add your own styles, you need to replace the existing style formats array with your own. Of course, you will have to add the styles to the stylesheet in the plug-in directory as well. If you need to use any image as background, you can create an image folder and reference the background image from there.

If you wish to use this in your theme, just add the plug-in code to the theme’s functions.php. Make sure to replace plugin_dir_url(__FILE__) with get_stylesheet_directory_uri() and reference the appropriate stylesheet from the theme folder.


Conclusion

Creative use of custom styles in the visual editor will make formatting the articles/posts and pages easier and a lot more fun. It will also make it easy for your clients to manage their websites and add life to it by including visually exciting content. By adding theme options, you can extend this plug-in so that the user can create their own custom styles for use in the visual editor.

All the best! Let us know in the comments how you would use this code and how you would extend it in your own usage.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.totalbounty.com Total Bounty

    I’d like to see how this works so let me check on this code and paste it in my file and see how it goes. Thanks for providing a really great tutorial!

  • http://www.vaultstudios.co.uk Martin Harvey

    Great Tutorial. I’ve implemented the Tiny MCE styles menu with custom styles previously in an effort to replace shortcodes in a theme. The only issue I have with this method is that when you have about 10+ styles, the dropdown does become a little un-user friendly, requiring you to scroll the menu. I’m looking for a way of doin the same as the styles menu but using a custom Tniy MCE button to open a pop-up to select the classes/styles from. Anybody any ideas?

    • http://www.ruturaaj.com Ruturaaj

      I second to this. I was about to post a request to show me how to add a custom button to the TinyMCE. I’ve attempted countless times and every time when I activate the button, all other buttons in HTML mode disappear. I know there is something missing in my editor_plugin.js file itself. I’ve gone through TinyMCE tutorials for creating custom plugins as well, but no luck. I left it aside simply because I was running short of time and some other responsibilities were calling me, challenging me. Today I read your tutorial and the same old bubble of curiosity about adding custom button to TinyMCE found its way to the surface. I’ve already added this to my task list for this week-end, in the meantime, if anyone can come up with a tutorial on adding custom button to TMCE, you’re most welcome!

    • http://www.speckygeek.com Pritam
      Author

      Hey Martin, Thanks for the idea of additional feature. A quick solution to your problem can be to categorize your styles and add multiple drop-downs for them.

  • Mike

    Ok… this is sweet. As a designer/developer this makes me happy. I can’t tell you how many times I’ve turned a project over to a client and they start to break the design guidelines I’ve set. This will help a lot. Curious, I’m just starting to crack TinyMCE and I’m on the hunt for a good tutorial on adding shortcode functions to the editor. I have a number of shortcodes I’m tired of writing all the time (mostly column layouts) and want to simplify that process. This tutorial wont interfere with my quest will it? Thanks for the knowledge.

    • http://www.ruturaaj.com Ruturaaj

      I feel,studding the code of WordPress Plugin, (such as Syntax highlighter and the range of its variants) to see how they have implemented a custom button with Popup and then process the values entered in the fields of Popup, should prove a better starting point for you to learn how to write your own Custom TinyMCE button for a short-code. Diving into TinyMCE code or its extensions may give you a hard time to understand some of the easy basics; trust me, I’m telling you this from my experience! :-)

      • Mike

        Ruturaaj, great idea. Thanks for the advice.

  • http://www.creativemanner.com ozgur coruhlu

    +1 to Martins request here. Thanks for the post btw.

  • Pingback: Adding Custom Styles in WordPress TinyMCE Editor | Shadowtek | Hosting and Design Solutions

  • http://www.villagranstudio.com Leandro

    Great tutorial!
    This really help as I don’t really like to use shortcodes because a lot of my clients they just don’t use them. One thing I do when I want clients to post text in certain way is to create a meta box so they can just put the desire text in there and then just style that accordingly.

  • http://webdesignergeeks.com Ajay Patel

    Nice one,
    Help me to give ready css using this to my client … thanks :)

  • http://www.wpfix.org Wpfix

    Nice wp tutorial on adding Styles in WordPress TinyMCE Editor

    :)

  • Pingback: Spanky Media Focuses on Social Media Integration for Website Development | Open Knowledge

  • Kartik

    Great Tutorial….. First of all i thought this was for adding custom button to editor but anyways i like the tutorial & hope it will help me a lot in future. I would love to see tutorial to add custom button. I tried many crazy things to add my button to editor but it never works well :D

    Thank you for great tutorial :)

  • Pingback: Как добавить свои стили в WordPress редакторе TinyMCE | Wordpresso

  • http://www.msrosyidi.com msrosyidi

    Great tutorial. But I’m still looking for how to add some button for styling the text to the wordpress comment form. I’ve created a shortcode for the commenters so they use that shortcode in the comment form to style some text. I want to give button for that so the commenters do not need to write the shortcode.

    • http://www.speckygeek.com Pritam
      Author

      There are plug-ins to allow rich-text formatting using TinyMCE in the comment form. You can find it on WordPress.org.

  • http://www.joshlobe.com Josh Lobe

    I have created a couple plugins based on this same concept. One of them has over 80 pre-defined custom styles, all added to the dropdown selector. I’m also learning how to implement the new CSS3 techniques into the editor via this method as well. Many are already available in the plugin.

    Here is the link to the page showing screenshots and examples:
    http://www.plugins.joshlobe.com/predefined-custom-styles/

    Thanks for allowing me to post here :)

  • Pingback: Link-Ecke #54 | campino2k

  • http://wesam.ly Wesam Alalem

    Great article, and helpful code. I’ve added the code to the functions.php directly.
    Thank you :)

  • http://www.htmlandphp.com Bladymir

    Fantastic solution! Very Helpful! Saved the day, Thank You!

  • http://13m2.nl Andre

    Very Cool, just what I was looking for.
    I ran a test and it works wonderfully.
    However, my new styles show up next to the rolldown which was already there.
    Which means that users can still mess up things by choosing styles from the wrong dropdown.
    Besides, i want to make the backend as simple as possible by removing clutter as to prevent confusion.

    Any ideas how to remove the rolldown that comes standard?

    Thanks

  • Toni

    This would be my holy grail (at least for this year).Can’t make it work though:

    1 Placed the code in function.php.

    2 Replaced plugin_dir_url(__FILE__) with get_stylesheet_directory_uri(). (2x)

    3 Referenced custom editor-styles.css (which is at same level as style.css of my childtheme). (2x)

    A) first function: $url .= trailingslashit( get_stylesheet_directory_uri() ) . ‘editor-styles.css’;

    B) last function: $StyleUrl = get_stylesheet_directory_uri().’editor-styles.css’;

    After refreshing page editor all my editor buttons are missing.

    Any clues?

    Tx,
    Toni

  • http://onlinegraphicscanada.com Woody House

    I have the basics working fine with the arrays nested inside the functions.php file but I am lost on how to create the custom STYLE (.css) code to support my own styles.

    If anybody could send me or upload a quick sample of their custom CSS file that works with the functions.php file, it would be appreciated.

    Have a great day and thanks for the great input.

    Woody House
    Online Graphics Canada

  • Mark Shirley

    I find it to clumsy to use

  • iflash

    Very nice Tutorial, just one step forward: how can we add some keyboard shortcut? If we want to use the Heading 1, just use the Ctrl+1 Shortcut.I figured out with buttons/shortcodes but I can’t with your dropdown style

  • Pingback: Top 160 Tutoriais WordPress – incluindo Basico, Desenvolvimento e Plugins – Site para Empresas – Blog sobre Internet e Criação de Site

  • Pingback: Deborah’s Weekly Web Resources Roundup: April 1, 2012