Using the JetPack plugin, WordPress supports using Markdown natively in the editor. This makes it much easier to write posts, but one feature has been a bit wonky — syntax highlighting.

Out-of-the-box, there’s no syntax highlighting plug-ins that met my need. Prism.js is a popular highlighter and while there are a few plugins to support it, the languages they pre-selected didn’t have what I wanted. Also, they didn’t seem to be regularly updated.

Fortunately, it wasn’t hard to create a child theme that contained a custom-downloaded version of the Prism JavaScript and CSS. I won’t walk through that part as it’s well documented elsewhere (see the previous link). What I did with the base child theme was to place my configured prism.js and prism.css files into a sub-directory and register them to be loaded by WordPress.

That almost worked. The trick is that Prism expects the syntax highlighting to be in tags matching <code class="language-foo"> where foo is whatever syntax rules it should apply. The trouble is that by default, JetPack’s Markdown -> HTML processor turns into <code class="json">. Seeing that, I hacked together a little fix-up script to inject prior to the prism code executing:

jQuery(function() {
    $ = jQuery;
    $("code").each(function() {
       var className = $(this).attr('class');
       if(className && !(className.lastIndexOf('language-', 0) === 0)) {
            // No language, prepend
            $(this).attr('class', 'language-' + className);
        }
    });  
});

Caveat: I am not a “real” JavaScript programmer; you might have a better way to do this!

When it was all assembled and uploaded to WordPress, I can now use the normal syntax and things get highlighted as expected.

I’ve zipped up my child theme that only contains these changes here.

You’re welcome to use that as a starting point; you’ll probably need to rename the child theme and specify the correct parent. You can also merge it with your current child theme.

As the Prism JavaScript and CSS is highly customizable, you may wish to generate your own from their site and use those in place.