Skip to content

How To Add A Custom Button To WordPress TinyMCE Editor

You know what’s the best part about using WordPress? You can customize WordPress just the way you want! Today, I’ll show you how to add a custom button to WordPress TinyMCE Editor. You can use this for your plugins or you can use your favorite button to TinyMCE

For those who are wondering, WordPress uses TinyMCE editor as its visual editor. So, we are going to use TinyMCE API to create a TinyMCE plugin. It’s really easy. Instead of using functions.php file, I’d recommend you to create a site-specific plugin for this task.

Registering A New TinyMCE Plugin

First, we need to register our button with WordPress to integrate it into the TinyMCE editor. Here’s the code:

add_action( 'init', 'code_button' );
function code_button() {
    add_filter( "mce_external_plugins", "code_add_button" );
    add_filter( 'mce_buttons', 'code_register_button' );
}
function code_add_button( $plugin_array ) {
    $plugin_array['mycodebutton'] = $dir = plugins_url( 'shortcode.js', __FILE__ );
    return $plugin_array;
}
function code_register_button( $buttons ) {
    array_push( $buttons, 'codebutton' );
    return $buttons;
}

Us used mce_external_plugins filter to register a new plugin to TinyMCE. We added the plugin ID (mycodebutton) and the URL pointing to our shortcode.js file, which will do the action. We also used mce_buttons hook to tell the TinyMCE which buttons in our plugin we want to show in the editor.

The codebutton is the ID value our button. We will create code button, which will wrap text in TinyMCE within the <code> element. We need to create shortcode.js file within our plugin folder, which will do the rest of the action.

Creating Buttons

Now, we will create shortcode.js file, which will be according to TinyMCE’s API. So, here’s the code that we will put in shortcode.js file:

(function() {
    tinymce.create('tinymce.plugins.code', {
        init : function(ed, url) {

            ed.addButton('codebutton', {
                title : 'Code',
                cmd : 'codebutton',
                image :  url + '//www.trickspanda.com/wp-content/swift-ai/images/code-png.webp'
            });

            ed.addCommand('codebutton', function() {
                var selected_text = ed.selection.getContent();
                var return_text = '';
                return_text = '<code>' + selected_text + '</code>';
                ed.execCommand('mceInsertContent', 0, return_text);
            });
        },
        // ... Hidden code
    });
    // Register plugin
    tinymce.PluginManager.add( 'mycodebutton', tinymce.plugins.code );
})();

First, we added the title, cmd, and image of the button Then, we added the action of our button. Our button will wrap selected code within a the <code> element.

Leave a Reply

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