A Perfect Syntax Highlighter for WordPress

Übersetzung verfügbar: Deutsch Deutsch

Finding a good and lightweight syntax highlighter wasn’t as easy as I thought. 

The first syntax highlighter I installed in my early WordPress days (i.e. 3 weeks ago) was Crayon. And it is definitively the prettiest of all. Unfortunately a real resource hog, too much of a resource hog for me. (The P3 Profiler is really good at detecting such things.)

The next one I tried was WP-GeSHi-Highlight. Very nice, too, but less nice than Crayon and only marginally less resource-intensive.

The third was Mivhak Syntax Highlighter. Finally a more lightweight highlighter but strangely it doesn’t have syntax support for everyday-things like Bash.

At the fourth try I hit the right one: Prism

It’s not a one-click installable thing, you have to choose a theme, the desired languages and optionally some extra features from the Customize page.

They offer six themes and about 60 languages (syntaxes) to choose from. Once made your selection you can immediately download the custom CSS and Javascript files. This has the nice advantage that you get a very slim package with only the stuff you really want. My Prism css file is 3K, the js file 15K, with 11 included languages and one extra feature.

After the download you drop the two files into the child theme folder and add these lines to your functions.php:

function add_prism() {
    // Register prism.css file
    'prismCSS', // handle name for the style so we can register, de-register, etc.
    get_stylesheet_directory_uri() . '/prism.css' // location of the prism.css file
    // Register prism.js file
    'prismJS', // handle name for the script so we can register, de-register, etc.
    get_stylesheet_directory_uri() . '/prism.js' // location of the prism.js file
    // Enqueue the registered style and script files

add_action('wp_enqueue_scripts', 'add_prism');

Now you are good to go, and it’s absolutely easy to use:

  • To invoke Prism on a code block you just have to add a class to the code tag, like this <pre><code class="language-php">.
  • To highlight inline code you would wrap the paragraph (or the whole text) in a div, like this <div class="language-markup"> … </div>.

It’s nice that it works with standard-compliant tags, so you won’t have problems in case you decide to no longer use it.

In rare occasions the highlighting is not 100% accurate but this is negligible. Not all of the extras work with every highlighting theme, for example I couldn’t get the line numbers showing up with the default theme. However the javascripts seem to be easily adaptable.

All in all, at the moment this is the almost perfect, super-lightweight syntax highlighter for me!

And, of course, it doesn’t work only with WordPress.

If you encounter problems installing it, there is a very good setup tutorial for WordPress available.