How to use custom styles in the WordPress post editor Published on July 27, 2010

Reduzir tamanho de letra Aumentar tamanho de letra Impressão optimizada do artigo Enviar por email

Every-time I created a word press theme, I felt the need to allow my theme users to use on their contents, the CSS styles that I had created to the theme itself.

They were especially created in order to maintain a visual identity between the layout and the contents, and should be directly applied at the author’s will! – How-come the styles, created specially for that theme (my CSS Classes), weren’t available to be applied trough the default WYSIWYG text editor?

My objective was allowing users to be able to apply the custom styles, in the default panel, using the panels own logic, without any particular knowledge of HTML or CSS and without having to stick to the editor’s default predetermined styles.

In this brief tutorial I’ll explain a very simple way to do this, just by adding a couple of lines of code to your theme’s functions.php, and by creating a very simple CSS file to host your custom styles.

In my previous article about this subject (www.wdmac.com/word-press-custom-css-styles-in-the-wysiwyg-editor) we’ve edited a couple of WP core files, and the result was satisfactory. However those edits where lost on every WP upgrade, and that was not satisfactory at all. This is a clean, straightforward technique, that is “permanent” and non-upgrade-dependent.

This article was updated: November 3th, 2011

1.We will start by creating the new CSS file.

The whole idea about creating a new CSS file, and not just adding your styles to the the theme’s default css file, is to allow you to use this technique in word press themes that you didn’t create, and that can be eventuality upgraded or updated whereas you’d loose all your custom styles with the update.

If you create a new CSS file to host your custom styles, you will never loose them even if the theme gets updated (or changed). Just link the new file to your theme and that’s it!

We’ll call it mycustomstyles.css and we will use it to create our theme’s custom styles

The styles bellow are just used for illustrative purposes and can allow, for instance, to position your images within your posts.

/* CSS Document
============================================ */
.fleft {
float:left;
margin-right:8px;
}
.fright {
float:right;
margin-left:8px;
}
/* Fim de CSS
============================================ */

2.Editing you theme’s functions.php

Typically all Word Press Themes have this file, wich can be found on your theme’s root folder.
What we will do is simply add the code-block bellow at the bottom of your functions.php, before it’s end, just above the php closing tag ?>

This code-block will then create a new select box in your word-press text editor, where your custom styles will be listed and applicable.

/* Custom CSS styles on WYSIWYG Editor – Start
======================================= */
if ( ! function_exists( ‘myCustomTinyMCE’ ) ) :
function myCustomTinyMCE($init) {
$init['theme_advanced_buttons2_add_before'] = ‘styleselect’; // Adds the buttons at the begining. (theme_advanced_buttons2_add adds them at the end)
$init['theme_advanced_styles'] = ‘Float Left=fleft,Float Right=fright’;
return $init;
}
endif;
add_filter(‘tiny_mce_before_init’, ‘myCustomTinyMCE’ );
add_filter( ‘mce_css’, ‘tdav_css’ );
add_editor_style(‘mycustomstyles.css’);
// incluiding the Custom CSS on our theme.
function mycustomStyles(){
wp_enqueue_style( ‘myCustomStyles’, get_bloginfo(‘stylesheet_directory’).’/mycustomstyles.css’, ”,”,’all’ ); /*adjust this path if you place “mycustomstyles.css” in a different folder than the theme’s root.*/
}
add_action(‘init’, ‘mycustomStyles’);

/* Custom CSS styles on WYSIWYG Editor – End
======================================= */

And by following these steps, your Word Press should be able to allow your theme users to use and easily apply your custom CSS styles directly in the word press WYSIWYG editor – TynYMCE.

EXTRA:

However, sometimes you don’t just wish to apply your own custom styles, but instead you wish to remove some of the predetermined styles from the text editor and your author’s reach… This way you could prevent unexperienced users to get confused by leaving them just the essential to produce quality content in their website!

For this special cases there is a possibility to remove some buttons the the default text editor, leavig just the ones you see fi, ar seem convenient to your needs.

To remove any of those buttons we will use a similar logic as used in step 2 above. We will just add another line in the condition created in the code-block at step 2.

3.Removing default styling buttons from the Word press default WYSIWYG editor

So, the in code-block created in step 2, we shall add a new line of code, as already shown bellow:

/* Custom CSS styles on WYSIWYG Editor – Start
======================================= */
if ( ! function_exists( ‘myCustomTinyMCE’) ) :
function myCustomTinyMCE($init) {
$init['theme_advanced_disable'] = ‘outdent, indent, justifyleft, justifycenter, justifyright, justifyfull, bullist, numlist, outdent, indent, fontselect, fontsizeselect, forecolor, backcolor, forecolorpicker, backcolorpicker, formatselect’; // Removes the undesired buttons
$init['theme_advanced_buttons2_add_before'] = ‘styleselect’; // Adds the buttons at the begining. (theme_advanced_buttons2_add adds them at the end)
$init['theme_advanced_styles'] = ‘Float Left=fleft,Float Right=fright’;
return $init;
}
endif;
add_filter(‘tiny_mce_before_init’, ‘myCustomTinyMCE’ );
add_filter( ‘mce_css’, ‘tdav_css’ );
add_editor_style(‘mycustomstyles.css’);
// incluiding the Custom CSS on our theme.
function mycustomStyles(){
wp_enqueue_style( ‘myCustomStyles’, get_bloginfo(‘stylesheet_directory’).’/mycustomstyles.css’, ”,”’,'all’ ); /*adjust this path if you place “mycustomstyles.css” in a different folder than the theme’s root.*/
}
add_action(‘init’, ‘mycustomStyles’);
/* Custom CSS styles on WYSIWYG Editor – End
======================================= */

No code created on step 2 was changed, just a new line of code was added. No further changes are needed.

By default these are the existing buttons on TinyMCE, distributed with Word-Press (3.0), that can be removed, should you wish to.

/* Default Buttons
* bold
* italic
* underline
* strikethrough
* justifyleft
* justifycenter
* justifyright
* justifyfull
* bullist
* numlist
* outdent
* indent
* cut
* copy
* paste
* undo
* redo
* link
* unlink
* image
* cleanup
* help
* code
* hr
* removeformat
* formatselect
* fontselect
* fontsizeselect
* styleselect
* sub
* sup
* forecolor
* backcolor
* forecolorpicker
* backcolorpicker
* charmap
* visualaid
* anchor
* newdocument
* blockquote
* separator ( | is possible as separator, too)
*/

Now you have some control over what your authors can or cannot do while using the text editor to create styled content.

Hope i’de save you some time, and avoided some catastrophes, that sometimes happen when you give too much power to someone who doesn’t know hoe to use it. I hope that your authors and yourself will now continue to produce quality contents, well formatted and visually coherent with the theme’s design.

This article was originally published in an article I wrote for the Portuguese Word Press Community blog: wp-portugal.com/2010/07/20/como-utilizar-estilos-proprios-no-editor-de-posts/

Download the code in TXT

Have fun!

MAC :)

PS: This article was written a while ago and since then WordPress has evolved.
The reader “Bones” has warned me about some improvements that were in order, and his suggestions are now included in the code above. Thanks mate!

38 comments on “How to use custom styles in the WordPress post editor”

  1. [...] More: How to use custom styles in the Word Press post editor | Web Design & Development Tutorials. Wor… [...]

  2. Håkan Folkesson says:

    I copied the code from your Spanish site because the code here did not work at first for me. I got it all up and running but it makes the WordPress admin pretty unstable for some reason. For example, after saving a post, a completely white page is returned. Also login is whacked up. The functionality works but since it makes WordPress unstable I can’t use it. Is this unstability coming from some 3.0.1 compability issue? Do you have any suggestion on how to fix it?

    Thanks/Håkan

    • WDMAC says:

      Hello Håkan

      There should be no problem with 3.0.1. I’ve tested it once more with WP 3.0.1, directly in Twenty Ten 1.1 theme, and it worked fine!

      However, you probably were right when mentioned this code was not working, probably from copy/paste encoding characters. Beware of copy-paste altering the character ‘ for ‘ wich will damage your code!

      I’ve removed the line numbers and pasted clean code. I’ve also uploaded a .TXT file with clean code that you can use without character problems. (www.wdmac.com/wp-content/uploads/customStyles.txt)

      Thanks for your feedback!

      MAC :)

  3. Josiah says:

    Thanks for the code Mac. Any ideas for how to load the styles without having to edit functions.php AND the custom style sheet? I realize the styles need names, but can they derive their names from the style name itself. Just looking to cut down the steps.

    Also a note to other folks implementing this code. A straight copy+paste from the code in the post will not work. Use the text file Mac provided above.

  4. Martin says:

    Hi, I tried this and it works great, but there’s one drawback – in the visual editor in the admin panel you can’t easily see what parts of the text have styles applied to them.

  5. Viva says:

    Nice tips !!!

    How can i set to show the advanced options by default, when a user logged in ?

  6. Martin says:

    Hi, thanks for this post!

    Interesting approach – i was searching a long time for something like this.. actually i did manage to delete some of those extra buttons. unfortunately i was not able to add a special style menu for my own styles. maybe it has something to do with the fact that i havent installed tinymce advanced because it breaks my 3.0.1 installation. can this be the reason or is there something else which should be done in order to get this working?

    i’m using your snippet like it is in the original, except that i deleted the following line:
    add_filter( ‘mce_css’, ‘tdav_css’ );
    thats because it breaks my user stylesheet somehow..

    do you have any ideas?
    your help is highly appreciated! thanks in advance..
    martin

  7. Bajola says:

    Hi,

    I just tried to use your modification, everything looks ok in the frontend and in the text editor in the backend, but there are 2 warnings in the bottom of the administration. Can you tell me, what does this mean and how to get rid of it? I don´t understand PHP that much to solve it, I think it can be related to CZ translation maybe. Thanks a lot

    Warning: file_get_contents(/home/www/mikroregion-lipensko.cz/subdomeny/www/wp-content/plugins/tinymce-templates/mce_plugins/plugins/template/langs/cs_dlg.js) [function.file-get-contents]: failed to open stream: No such file or directory in /home/www/mikroregion-lipensko.cz/subdomeny/www/wp-content/plugins/tinymce-templates/mce_plugins/plugins/template/langs/langs.php on line 4

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘tdav_css’ not found or invalid function name in /home/www/mikroregion-lipensko.cz/subdomeny/www/wp-includes/plugin.php on line 166

  8. Bajola says:

    I just solved the first warning. It was connected with a different plugin, where a CZ file missed. But the second one still remains to solve.

  9. Irian says:

    Hi,
    I realy like this post, but when I tried to apply the code (from the .txt) to my WordPress, no tinyMCE buttons are displayed at all!
    Any idea on how to solve this?
    Thanks!
    Irian

  10. Ryan says:

    Thanks for this. Just what I was looking for. *I approve your legendary status*

    However not having an admin friendly WYSIWYG was a loss.

    So just edited wp-includes/js/tinymce/themes/advanced/skins/wp_theme/content.css to allow users to see a bold header when style is applied. (Since it was a CHMOD permission based file I just deleted and repasted the same file with the new custom classes).

  11. Barbara says:

    I’m running WP 3.1, and this modification doesn’t add a drop-down box in the editor. It looks like this doesn’t work in 3.0+

    • WDMAC says:

      Hello Barbara, thanks for yuor feedback.

      This tutorial was written before the 3rd series, so you may have a point here.

      While writing this reply, I just interrupted and tried writing a new post to see if the drop-box had disappeared.

      But no. I’m running WP 3.0.5 and the boxes are there!
      they are only visible in the visual editor mode, on the second line [show/hide advanced options (Alt+shift+z)]

      I’ll now upgrade WP to 3.1, and I’ll let you know. If i see any problems, I’ll update the tutorial.

      Thanks

      MAC :)

  12. Ehud says:

    Great tutorial, I managed to create a dropdown and remove some buttons easily on wp3.1.

    Only drawback was that the backend interface got terribly out of whack – especially around the header. Then I realized it’s because I was importing the main stylesheet using bloginfo(stylesheet_url). Now I have just the selectors defined in a custom css file imported from bloginfo(stylesheet_directory)/custom.css. Works great.

    Many thnaks!

  13. Paul says:

    BRILLIANT!!!!

    This is great… Yes clients can…. and regularly do…. really make a mess of things don’t they ….

    “With great power comes….. a great ability to screw things up” … :-)

    I just wanted to clarify a couple of things, in case I am (and maybe others are) missing something…..

    1. This just gives the ability to apply custom styles in the editor. The editor won’t actually “display” the applied styles inside the editor… right?

    2. likewise the custom stylesheet won’t automatically be used by the template files in the theme… right?

    If that is correct (and I’m not missing anything) then adding

    @import url(‘/wp-content/themes/child_theme/mycustomstyles.css’);

    to the top of your themes styles.css, will stop the need to duplicate the styles.

    One more thing after I implemented your code…. I thought people might find useful

    If you’re using a child theme (as of course you should be) and your new custom stylesheet is also in your child directory then instead of

    get_bloginfo(‘template_url’).’/mycustomstyles.css’

    use

    get_stylesheet_directory_uri().’mycustomstyles.css’

    Thanks again for this invaluable little gem!!!

    Now if someone can just tell me how to attach a customizable wysiwyg editor like this one to widget textareas, then athat really would be something!!!!

    I’ve tried a couple of plugins and a few hacks but no simple (relatively speaking) solution that works … any thoughts ???

    Thanks again MAC

    :-p

  14. T says:

    thanks for this. this got the style selection box to show up.. but when i applied it to text, tinymce didn’t actually change the text. to get this to work, i had to add the following additional line after the init lines

    $init['content_css'] = get_template_directory_uri().’/.css’;

    this tells TinyMCE to load this css file

    i also had to modify my header.php to include the custom css file.

    thanks again!

  15. T says:

    that should be your-custom.css above not “.css”.

  16. Gunela says:

    Many thanks to everybody, I’ve been stucked for a few days but I did it finally!!

    I’m not an expert but using the method suggested by WDMAC I’ve loaded my css file..

    Just a question: in the drop-down menu referring to the “link insert/modify” window, only my new class appears and not any longer the former ones (wp-align, wp-Gallery etc…). Is this an expected behaviour?

  17. Davide says:

    Hi all, I’ve applied the script to my blog. I’m trying to do the best I can but still I’m not able to apply the simple style I’ve created.

    First of all, I’ve created this “mycustomstyles.css” in the theme’s root folder (I’m using koi):

    /* CSS Document
    ============================================ */

    .linkazzurro a {
    color: #3366ff;
    text-decoration: underline;
    outline: none;
    }
    .linkazzurro a:hover {
    color: #3366ff;
    text-decoration: none;

    /* Fine del CSS
    ============================================ */

    then I’ve added this section, before the ending “?>”, of functions.php:

    /* Custom CSS styles on WYSIWYG Editor – Start
    ======================================= */
    if ( ! function_exists( ‘myCustomTinyMCE’ ) ) :
    function myCustomTinyMCE($init) {
    $init['theme_advanced_disable'] = ‘outdent, indent, justifyleft, justifycenter, justifyright, justifyfull, bullist, numlist, outdent, indent, fontselect, fontsizeselect, forecolor, backcolor, forecolorpicker, backcolorpicker, formatselect’; // Removes the undesired buttons
    $init['theme_advanced_buttons2_add_before'] = ‘styleselect’; // Adds the buttons at the begining. (theme_advanced_buttons2_add adds them at the end)
    $init['theme_advanced_styles'] = ‘Link Azzurro=linkazzurro’;
    $init['content_css'] = get_template_directory_uri().’/mycustomstyles.css’;
    return $init;
    }
    endif;
    add_filter(‘tiny_mce_before_init’, ‘myCustomTinyMCE’ );
    // incluiding the Custom CSS on our theme.
    function mycustomStyles(){
    wp_enqueue_style( ‘myCustomStyles’, get_bloginfo(‘template_url’).’/mycustomstyles.css’, ”,”,’all’ );
    }
    add_action(‘init’, ‘mycustomStyles’);
    /* Custom CSS styles on WYSIWYG Editor – End
    ======================================= */

    The editor, at this point, shows both the button and the style inside the drop-down menu of the link insertion/modify window. Inside HTML tag I can see the class “linkazzurro” applied to the link but I don’t see it inside the Preview and, of course, in the website.

    I’ve added inside header.php, without any effect. Am I wrong in same step? Unfortunately I’m a newbie so this problem is driving me crazy!!! Has somebody an idea?

    • niyas k says:

      thanks yar,
      it really works for me, can list styles on drop down form a custom css file.

      i also removed the default drop down styles on :
      wordpress/wp-includes/js/tinymce/plugins/wordpress/css/content.css and
      wordpress/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/content.css

      now only custom css file styles taken,thanks :)

  18. Davide says:

    I apologize, I haven’t pasted, in the last section of my comment, what I added inside header.php:

  19. Davide says:

    I can’t paste the header.php modification therefore I comment it:

    /**/

  20. Davide says:

    No way to paste it, in any case it was a link rel with type and href with an absolute path to the css starting from wp-content…

  21. Remove my comment if I am wrong, but I think that it would be better to use
    admin_init
    rather than
    init
    for things that you want to happen only in the Admin area.
    Then WP isn’t bothering to load extra code when just displaying a regular page for non-admin.
    add_action(‘admin_init’, ‘mycustomStyles’);

    • WDMAC says:

      Hi Brian

      Your are absolutely right in principle. However in this particular case I need the styles to be loaded to the front-end, and not just in the admin area.

      The all point is letting people use and apply custom styles trough the WYSIWYG editor so they can be “interpreted” in the front-end to the general public.
      If my styles or scripts were only to be used in the admin area, then, admin_init (or eventually admin_head) were indeed the correct hooks to use.

      Thanks!

      MAC :)

  22. Ian Hackett says:

    I seem to be having a problem with this.
    After adding the code to my functions.php file, i get this at the bottom of my editor pages.
    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘tdav_css’ not found or invalid function name in C:\xampp\xampplite\htdocs\websites\wordpress\wp-includes\plugin.php on line 170.
    Also, all the TinyMCE buttons have disappeared, and the page layout has gone a bit funny and out of place.
    What’s gone wrong?

  23. Shane says:

    When I add the code to my functions.php file it causes the text in the editor to go white so I can see it and disables the visual editor altogether. I am using version 3.2.1
    Any idea what I can do to get this working?
    Thanks!

  24. Bones says:

    Hello.

    Nice guide, still i think there are some proablems.

    1. the line below is useless, and should be deleted.
    add_filter( ‘mce_css’, ‘tdav_css’ );

    2. the following line:
    wp_enqueue_style( ‘myCustomStyles’, get_bloginfo(‘template_url’).’/mycustomstyles.css’, ”,”’,’all’ );

    would work better if changed in:
    wp_enqueue_style( ‘myCustomStyles’, get_bloginfo(‘stylesheet_directory’).’/mycustomstyles.css’, ”,”’,’all’ );

    3. the following line should be added. it helps make the editor look like the custom css.
    add_editor_style(‘mycustomstyles.css’);

    Your guide plus my changes worked graite for me. I hope it will help others.
    Thx for the guide.

    • WDMAC says:

      Hi Bones

      Thanks for your warnings.
      I’ve updated the code to your suggestions, except for point 1, where I haven’t had the time, yet, to check.

      Thanks!

      MAC :)

  25. Andre says:

    Cool tutorial. I’ve been searching the web for quite some time now. I do find solutions but most seem to be about *adding* styles to the dropdown, while I thing deleting things you don’t need is just as important. If you care about giving the user an uncluttered editor, which will not confuse her.

    However, I can’t get it to work in 3.4
    got an error like this after logging in:

    Fatal error: Call to undefined function is_rtl() in /home/mycustomer/domains/example.com/public_html/wp/wp-includes/theme.php on line 1174

    Any idea how to solve this?

    Thanks

  26. Andre says:

    OK found it.
    I had a plugin that I tried earlier still in my plugins folder (something like ATG or AGR dropdown that caused the conclict0
    Deleted that and now it’s ok

    feel free to not publish my earlier comment

    cheers

  27. Tom says:

    I am using a twenty eleven child theme.

    Followed your tutorial to the letter. However – I copied the functions.php into my child theme.

    That breaks the admin back-end. Blank white page.

    Can you provide any tips on how to approach this using a child theme?

    I’m fairly new to WordPress.

    Thanks!

  28. Growlay says:

    Great tutorial, thanks.

    I notice that this post is dated although recent replies are still relevant to my case. This tut appears to solve what I consider a great shortcoming.
    I had been assured that upgrading itself would solve it but does not.

    Should I expect to have to modify this for a WP 3.4.1 install?
    Does anyone have pointers for doing so, or perhaps there are relevant links elsewhere?

    I’m currently experiencing a combination of “white screen” and “fatal error” mentioned above.

Go ahead! Leave your comment on this subject!

Fields marked with (*) are mandatory!

Spam Protection by WP-SpamFree

Resources
Goodies & Infos
Earn Extra Money!

Get an extra income with your vacation photos!

TIP: go to Shutterstock, submit your photos and make an extra income every month. - I do!

MAC

 

Categories

 

External Resources
Twitter Updates
    © 2010 - WDMAC A Blog about Web Design & Development. WordPress development. Tutorials - "Proudly powered by WordPress!"