Create WordPress TinyMCE Color Picker Button

In today tutorial, I will show you how to add WordPress TinyMCE editor button that can handle Color Picker function when adding shortcode.

Step One – Initiation

I will be using twentysixteen theme for adding the button. So let’s create a directory called colorpicker inside twentysixteen theme root, then add a new colorpicker/colorpicker.php file and copy these codes below:

<?php
    define( 'NSC_PATH', trailingslashit( get_template_directory() ) . 'colorpicker' );
    define( 'NSC_URL',  trailingslashit( get_template_directory_uri() ) . 'colorpicker' );
    
    require_once( 'tinymce/init.php' );
?>

Then we will require the file in twentysixteen functions.php, open it and add this line to the last line of the file

require_once( 'colorpicker/colorpicker.php' );

Next create tinymce directory inside colorpicker directory then create another two files which are tinymce/init.php and tinymce/plugin.js.

Let’s work on tinymce/init.php, define a class for our initiation file

<?php

if ( ! defined( 'ABSPATH' ) ) exit( 'No direct script access allowed' ); // Exit if accessed directly
class NSC_Tinymce_Init {
    function __construct() {
        add_action( 'init', array( $this, 'init' ) );
    }
}
?>

Step Two – Register TinyMCE Plugin

We will use init method to add callback function on admin_init action to register our button.

function init() {
    add_action( 'admin_print_styles', array( $this, 'print_styles' ) );

    if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) )
        return;

    if ( get_user_option('rich_editing') == 'true' ) {
        add_filter( 'mce_external_plugins', array( $this, 'add_rich_plugins' ) );
        add_filter( 'mce_buttons', array( $this, 'register_rich_buttons' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_script' ) );
    }
}

First, we check for rich editing feature is enabled or not by the current user if it’s enabled we specify some callback for actions and filters here to register our button and the action handler for the button:

  • mce_external_plugins. This filter may be useful for loading any of the TinyMCE core plugins, many of which are not included by default in WordPress, as well as any custom TinyMCE plugins you may want to create.
  • mce_buttons.  Can be used by developers to add or remove buttons/features from the WordPress’s TinyMCE toolbar(s). If you want to add to the second row of the TinyMCE toolbar, used mce_buttons_2.
  • admin_enqueue_scripts. Similar to wp_enqueue_scripts but only for admin area, which used to register our custom javascript file.
  • admin_print_styles. We will need to add our custom css style here for styling the TinyMCE button a little bit.

Here are the codes for each callback:

Register the plugin data for TinyMCE

/**
 * Defins TinyMCE rich editor js plugin
 */
function add_rich_plugins( $plugin_array ) {
    /* we will call our TinyMCE plugin nscShortcodes */
    $plugin_array['nscShortcodes'] = trailingslashit( NSC_URL ) . 'tinymce/plugin.js';
    return $plugin_array;
}

Register the Button

/**
 * Adds TinyMCE rich editor buttons
 */
function register_rich_buttons( $buttons ) {
    array_push( $buttons, "|", 'nsc_button' ); // nsc_button will be our unique ID for the button */
    return $buttons;
}

Enqueue Color Picker files

function enqueue_script() {
    wp_enqueue_script( 'wp-color-picker' ); // the wp-color-picker javascript file
    wp_enqueue_style( 'wp-color-picker' ); // the wp-color-picker css file
}

Print Style

This will add some styles to fix our broken color picker cause by TinyMCE styles and to styling the button icon in TinyMCE toolbar.

function print_styles() {
    $icon = trailingslashit( NSC_URL ) . 'tinymce/icon.png';
    echo '<style>
        .mce-ico.mce-i-nsc-tinymce-icon{ background: url("'.$icon.'") no-repeat; } 
        .mce-container .wp-picker-container { display: inline-block; margin: 10px; }
        .mce-container .wp-picker-input-wrap input.mce-colorpicker {
            width: 65px !important;
            position: static !important;
            float: left;
            margin: 0;
            line-height: 1;
        }
        .mce-container .wp-color-result {
            background-color: #f7f7f7;
            border: 1px solid #ccc;
            border-radius: 3px;
            box-shadow: 0 1px 0 #ccc;
            cursor: pointer;
            display: inline-block;
            height: 22px;
            margin: 0 6px 6px 0;
            padding-left: 30px;
            position: relative;
            top: 1px;
            vertical-align: bottom;
        }
	</style>';
}

Step Three – Create TinyMCE Plugin

To add a new plugin to TinyMCE, we will need to call the TinyMCE plugin manager:

    tinymce.PluginManager.add( 'plugin_name', callback[ editor, url ] );

Let’s go adding our nscShortcodes plugin:

tinymce.PluginManager.add( 'nscShortcodes', function( editor, url ) {

    });

We will add our new button as menu button in TinyMCE toolbar, to add button add these codes inside the callback function:

tinymce.PluginManager.add( 'nscShortcodes', function( editor, url ) {
    var menuOptions = [];
    editor.addButton( 'nsc_button', {
        icon: 'nsc-tinymce-icon', /* icon class name *.
        title: 'Insert Color', /* button title */
        type: 'menubutton', /* the type is menu button */
        menu: menuOptions /* our handler for the menu button */
    });
});

Button Options

Since our button is a menu button, we will need to register the options array for the menu and register our shortcode action and initiate the colorpicker.

    var menuOptions = [{
        text: 'Color Picker',
        onclick: function() {
            /*Action for when the menu button is clicked */
            editor.windowManager.open({
                title: 'Insert Color', /* Modal Title */
                width: 500, /* Modal Height */
                height: 500, /* Modal Width */
                body: [{
                     type: 'textbox', /* field type */
                     name: 'color', /* field name */
                     classes: 'colorpicker', /* field class */
                     value: '',
                }], /* Modal body content */
                onsubmit: function(e) {
                    /* this will add the shortcode strings to the editor visual tab */
                    editor.insertContent( '[nsc-color value="' + e.data.color + '"]' );
                }
            });
            /* Initialize our Colorpicker */
            
            var windows = editor.windowManager.getWindows()[0]; /* get current opened windows */
            var $el = jQuery( windows.$el[0] ); /* get the container object */

            /* check if wpColorPicker available */

            if( typeof jQuery.wp === 'object' && typeof jQuery.wp.wpColorPicker === 'function' ) {
                /* BY DEFAULT TINYMCE WILL ADD mce- PREFIX TO THE CLASS
                $el.find( '.mce-colorpicker' ).wpColorPicker();
            }
        }
    }];

Note: By default tinymce will add mce- prefix to the classes you have defined for each field.

So That’s all, now try to create a new post / page and hit the TinyMCE button we just registered and get the color value :D.

Source code available here: colorpicker

One Comment

  1. It helped a lot, thank you for sharing. Strangely, I didn’t had to include any of the previous code, only the last part for a button. Maybe colopicker was included by default on my theme (Newspaper).

Leave a Reply

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