Colours pallet to WordPress visual editor

This code snippet add a colour picker for  text or background colour found inside the visual editor  toolbar with a customisable colour grid.

The Code

Just add the following block of code to your theme’s functions.php file, and customise to suit your requirements:

Explaining the Code

Before the TinyMCE toolbar is initialised, it calls the tiny_mce_before_init hook.

We create a function called wptb_tinymce_options that will run when this hook is called, by registering it with the tinymce_before_init hook:

function ($init){
//Do stuff<
}
//We register our function to run when the tiny_mce_before_init hook fires:
add_filter('tiny_mce_before_init', 'ns_mce4_options';

Our function receives an array of TinyMCE $init. Since we receive this array before the TinyMCE component initialises, we can modify it before everything is rendered to the screen.

One of the items in this array is $init[‘textcolor_map’], which contains a specially-formatted string of colours and colour names. By replacing this string with our own, we can override the built-in colour palette.

    $custom_colours = '
        "3366FF", "Color 1 name",
        "CCFFCC", "Color 2 name",
        "FFFF00", "Color 3 name",
        "99CC00", "Color 4 name",
        "FF0000", "Color 5 name",
        "FF99CC", "Color 6 name",
        "CCFFFF", "Color 7 name"
    ';

    // build colour grid default+custom colors
$init['textcolor_map'] = '['.$custom_colours.']';

Lastly, the hook expects us to return the updated $init array so that the TinyMCE Editor can complete initialisation:

return $init;

ABOUT AUTHOR

Nuno

I am a Freelance Web Developer and WordPress Expert based in London with a wealth of website development and support experience. I am great at problem solving and developing quick solutions.

LEAVE A COMMENT

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • LET'S TALK!

    Fill in the form below to make an enquiry or find my contact details on my contact page.

  • This form collects your name and email address so that I can respond to the enquiry(ies) that you submit via this website. Please check my privacy policy for the full story on how I use, protect and manage your submitted data.