How to highlight code with “Code Syntax Block” snippets?

Short version

Long version

I am using https://wordpress.org/plugins/code-syntax-block/ plugin but I did not notice in their documentation how to use it. I had to find a way myself. But problem is at the same time an opportunity – I can write an article for that 🙂

So I have installed plugin and try adding code in a WordPress way – click + icon and chose code:

I paste the code and if I preview my page – code is black and white. It does not automatically detect language – like this:

It is better than nothing. But still it would be nicer if there were colors. I saw probably in docs that it uses prism js library for that. So I searched for example how to highlight code with that library. And on https://prismjs.com/ I see this example:

<pre><code class="language-css">p { color: red }</code></pre>

So in the example they add class=”language-css” to code tag. I have added to code tag that class but I was getting error “This block contains unexpected or invalid content”. This starts to be annoying. Such a simple thing, used on many websites and I cannot do it quickly. Tried to play a guessing game – add this class to <pre> tag instead of <code> tag. And turns out it works. Sometimes coding is like this. It should work in one way but works in other way and you have to guess that other way 🙂 But if you found this article maybe you solved that issue faster than I had to do. In case it was helpful, I would be happy to know.

And also in case you did not see how to add the class – you need to click on the code block 3 dots and in the menu select “Edit as HTML”:

And now you get html with <pre> and <code> tags. In the <pre> tag – add class “language-css” if this is css language and same pattern for other languages:

Also if you want to add and highlight html code to the post, add the html in visual mode, not in “Edit as HTML” mode. This is needed so that html would be escaped. Otherwise it does not work. After adding html in visual mode and clicking “Edit as HTML”, html looks like this – your site code is not escaped, it will be parsed by browser and inside code tag there is escaped html like this:

This code works with Twenty NineteenVersion: 2.1 theme.

Thanks for reading, happy posting 🙂

Leave a comment

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