Flatsome Add a Code Highlight Button or Tag HTML to the TinyMCE Toolbar

23 Apr 2020
0 Comments

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.

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=https://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.

javascript Donate
                
                    
(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.

Similar solution but smarter thanks to tinymce documentation

                
                    
add_action('admin_head', 'sweb_shortcode_button');
function sweb_shortcode_button() {
    global $typenow;
    // check user permissions
    if ( !current_user_can('edit_posts') && !current_user_can('edit_pages') ) {
        return;
    }
    // verify the post type
    if( ! in_array( $typenow, array( 'post', 'page', 'blocks', 'product' ) ) )
        return;
    // check if WYSIWYG is enabled
    if ( get_user_option('rich_editing') == 'true') {
        add_filter("mce_external_plugins", "sweb_shortcode_add_tinymce_plugin");
        add_filter('mce_buttons', 'sweb_shortcode_insert_button');
    }
}

function sweb_shortcode_add_tinymce_plugin($plugin_array) {
    $plugin_array['sweb_shortcode_insert'] = get_theme_file_uri( '/change/tinymce/shortcode_insert.js' );
    $plugin_array['code'] = get_theme_file_uri( '/change/tinymce/code.js' );
    return $plugin_array;
}

function sweb_shortcode_insert_button($buttons) {
//    array_push($buttons, "subscript");
//    array_push($buttons, "superscript");
    array_push($buttons, "sweb_shortcode_insert");
    array_push($buttons, "code");

    return $buttons;
}
                
            
javascript Donate
                
                    
tinymce.PluginManager.add('code', function(editor, url) {
    // Add a button that opens a window
    editor.on('init', function() {
        editor.formatter.register('code', {
            inline: 'code', classes: 'language-markup'
        });
    });
    editor.addButton( 'code', {
        text: 'Code',
        icon: 'icon dashicons-editor-code',
        tooltip: 'Code Tag',
        onclick: function () {
            // console.log(tinyMCE.activeEditor.selection.getContent({format: 'text'}));
            editor.execCommand('mceToggleFormat', false, 'code');
        },
        onpostrender: function() {
            var btn = this;
            editor.on('init', function() {
                editor.formatter.formatChanged('code', function(state) {
                    btn.active(state);
                });
            });
        }
    });
});
                
            

There are a few links for you to learn more here:

https://community.tiny.cloud/communityQuestion?id=90661000000IjGiAAK

Add a Code Highlight Button to the TinyMCE Toolbar

https://github.com/audrasjb/tinymce-abbr/

TinyMCE Annotate

Update TIPS: I have 1 more simpler solution

                
                    
add_filter( 'flatsome_text_formats', 'fs_tinvn_flatsome_text_formats' );
function fs_tinvn_flatsome_text_formats($style_formats){
   $array = array(
      'title' => 'Sweb Class',
      'items' => array(
            array(
                'title' => 'Code',
                'inline' => 'code',
                'classes' => 'flatlineui-code',
                'wrapper' => false,
//                'styles' => 'background-color: #eee',
            ),
         array(
            'title' => 'Margin bottom 0',
            'selector' => 'h1,h2,h3,h4,h5,h6,p',
            'classes' => 'mb-0',
            'exact' => true,
         ),
         array(
            'title' => 'Is normal',
            'selector' => 'h1,h2,h3,h4,h5,h6,p',
            'classes' => 'is-normal',
            'exact' => true,
         ),
            array(
            'title' => 'Table Class',
            'selector' => 'table',
            'classes' => 'flatline-table',
            'exact' => true,
         ),
      )
   );

   if (get_tinvn_base_mod("string_class_tiny_mce")) {
       //fs-title-divider=h1,h2,h3,h4,h5,h6,p
        $extra_list_styles = get_tinvn_base_mod("string_class_tiny_mce");
        $extra_list_styles = explode("\r\n" , $extra_list_styles);
        foreach ($extra_list_styles as $item){
            $item = explode("=", $item);
            if (count($item) >1) {
                array_push($array["items"], array(
                    'title' => $item[0],
                    'selector' => $item[1],
                    'classes' => $item[0],
                    'exact' => true
                ));
            }

        }
    }
   $list_styles = array(
      'title' => 'Bullets List - Circle',
      'selector' => 'ol,ul',
      'classes' => 'bullet-circle',
   );

    $list_styles_1 = array(
        'title' => 'Bullets List - Dot',
        'selector' => 'ol,ul',
        'classes' => 'bullet-dot',
    );

   array_push($style_formats[9]['items'],$list_styles);
   array_push($style_formats[9]['items'],$list_styles_1);
   array_unshift( $style_formats, $array );
   return $style_formats;
}
                
            

Leave a Reply

This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our use of cookies.