WordPress Syntax Highlighting (Colours) for Code Blocks

You may have noticed that the code examples I use on this site (which runs on WordPress) use a default <code> block, but the code is presented with different colours due to code block syntax highlighting.

On my site I use the new (at the time of writing this) WordPress 5 ‘Gutenberg’ editor, which has a nice ‘code block’ feature, allowing you to drop in a code block and start writing code, without all that mucking about in HTML.

WordPress 5 Gutenberg Code Block
WordPress 5 Gutenberg Code Block

By default the blocks are a presented as boring and plain, with not a colour in sight, but thanks to the plugin Code Syntax Highlighting in Gutenberg by Marcus Kazmierczak who works at Automattic, I’ve transformed my plain old code blocks into something wonderful.

Let’s take a look:

Before

/**
 * Yawn \(´O`)/
 **/
function my_boring_code_block() {
    $dont_i_look_dull = true;
}

After

/**
 * Wow! ヽ(•‿•)ノ
 **/
function my_interesting_code_block() {
    $dont_i_look_lovely = true;
}

Marcus has extended the default code block to have a new ‘block setting’ so that you can apply syntax highlighting selectively to any code block on your site:

Code Block Extended Settings
Code Block Extended Settings

You can grab Marcus’s syntax highlighting plugin by visiting his website.

What About those Gist things?

A lot of the code embeds on my website use embedded Gists from GitHub.

Gists are a great way to share snippets of code that don’t necessarily belong in a project. They come with some great syntax highlighting.

Just copy and paste the Gist into your editor and boom, a nice formatted code snippet!

Oh Wait, That Didn’t Work!

Oh yeah, Gist oEmbed isn’t supported by default in WordPress. Never fear, there is a plugin for that!

I use oEmbed Gist by Takayuki Miyauchi which lets you simply paste a link to the Gist that you want to embed, and WordPress handles the rest!

What About Syntax Highlighting in Legacy Sites?

All you luddites, never fear, I would recommend the Crayon Syntax Highlighter plugin for all of your shiny code example needs!

It gives you loads of options, and works pretty well.

Posted by Matt Watson

Matt Watson is co-founder of the WordPress agency Make Do. Matt loves learning about personal, professional and web development. Learn more about Matt.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.