Add a Code Highlight Button to the TinyMCE Toolbar

I was looking for an easy way to add a code highlight button to the WordPress default editor. More precisely, to the toolbar of TinyMCE. It should have one job: to add <code> ... </code> tags around the selected text. It’ll also wrap or unwrap a single word where the cursor is blinking.  Surprisingly, this feature is far from being a WP core thing. Even though I see this in articles everywhere, I can only hope writers aren’t wrapping text in code tags by hand.

Why add a custom button?

There is a native code highlight button on the “Quicktags toolbar”, but you need to switch to the Text tab to reach it. I find that inconvenient.

Code highlight button on quicktags toolbar

What’s worse is that this doesn’t even support unwrapping, and defeats the purpose of a WYSIWYG editor. If I wanted to decorate my writing with markup code, I’d use markdown. I feel the toolbar-based visual editor (TinyMCE) is one step towards the live preview editors or builders (Gutenberg or Elementor). Whereas using markdown would be two steps back towards the era of phpBB forums, no offense. You know, when people had to write links as [url=http://www.phpbb.com/]link[/url]. I was hoping that time has passed by now. I’m unsure how long until Gutenberg takes over and makes TinyMCE-related addons useless in WordPress. In the meantime, here is how we do it!

The solution: a real code highlight button!

The following snippet goes into your functions.php file (of your child theme). It registers a plugin for TinyMCE toolbar in the form of a single code highlight button. If you want to add other buttons, do so below line 6.

function lwp_1133_tinymce_plugin( $plugin_array ) {
    $plugin_array['lwp_1133_tinymce'] =
        get_stylesheet_directory_uri() . '/mce_extras.js';
    return $plugin_array;
}
function lwp_1133_tinymce_buttons( $buttons ) {
    $buttons[] = 'lwp-code';
    return $buttons;
}
function lwp_1133_tinymce() {
    $screen = get_current_screen();
    if ( $screen->base !== 'post' ) return;
    add_filter( 'mce_external_plugins', 'lwp_1133_tinymce_plugin' );
    add_filter( 'mce_buttons', 'lwp_1133_tinymce_buttons' );
}
add_action( 'current_screen', 'lwp_1133_tinymce' );

And add this to a mce_extras.js file that you create in the same folder. It adds a new format that is an inline code tag with the class inline-code-highlight along with a button. It’ll also make its button active if you discover these areas in the text with your cursor.

(function() {
    tinymce.PluginManager.add('lwp_1133_tinymce', function(editor, url) {
        editor.on('init', function() {
            editor.formatter.register('lwp-code', {
                inline: 'code', classes: 'inline-code-highlight'
            });
        });      
        editor.addButton('lwp-code', {
            title: 'Inline code',
            icon: 'code',
            onclick: function() {
                tinymce.activeEditor.formatter.toggle('lwp-code');
            },
            onPostRender: function() {
                var ctrl = this;
                editor.on('NodeChange', function(e) {
                    ctrl.active(
                        e.element.className.indexOf('inline-code-highlight') !== -1
                    );
                });
            }
        });
    });
})();

The result is simply a code highlight button that is easy to use. You might want to style it with Custom CSS like we do. Feel free to take this further and create one for the HTML5 <mark> ... </mark> tag too to highlight standard text. We use 13 different buttons, but they all follow the same principle. Instead of copy pasting the above code many times, I wrote some loops not to repeat myself. Why so many? We use these to add the pre tags by language which makes the above colorful code snippets possible. As you can see, our syntax highlighter plays nicely with these 1-click shortcuts.

Related Posts

Leave a Reply

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

Join Our Newsletter!

Get secret tips and valuable details about making your site more successful.

Follow Us!

We Recommend

This site is powered by Elementor

100% Free  WP Website Builder  All-in-One Solution

Monthly Archives

Scroll Up