Code highlighting is not a standard feature on WordPress. This is understandable since most WP users don’t need this option – and even those who do, have different preferences about the way they want to display their code.
Note: The following procedure works only if you are self-hosting your WordPress blog.
After looking around I’ve decided to use Prismjs, which is very lightweight and easy to install once you become familiar with the procedure.
When customizing theme-files, it is advisable to create a sub-theme, which is also known as a theme child on WordPress lingo. This is because any code customization performed in the original theme will be lost the next time the original theme is upgraded and that can happen automatically. Fortunately, this procedure is easier to do than what it sounds.
- Following the instructions from the URL given below, I created a theme-child instance in a matter of minutes (thanks Nick):
Later, if you want to know more about this topic, WordPress has a nice section about sub themes:
- Once I had a child theme instantiated and properly working, the next step was to download Prismjs from source:
For that, I followed the easy instructions given on crambler.com:
and here it is:
let func = 123;
There are a couple of things to consider when using Prismjs
- While editing a post, the highlighting is not visible to me and that is confusing at first. However, we can see the difference when previewing the text.
- You need to choose one of the several color themes available from source before downloading. After trying all of the themes on my blog (which is an easy operation once the initial setup is done), I settled for the “Twilight” theme (see on this post).
- Line numbers are one of several plugin-options you can select before downloading the files.
How to configure the code to be displayed
Here’s how I did it for the example shown before (small screen users, please slide the code-window horizontally to see the whole script):
Above, there are two classes connected together. The line-numbers class does not have to be there unless you want line numbers.
Speaking of line-numbers, you can use the data-start=”number” attribute to start your line on a number other than 1. See below:
Well, I hope this little adventure comes handy for someone out there. I was an avid user of WordPress in the early days but it has been more than a decade since my last installation. So much has changed since then.
How do you currently highlight the code you post in your blog? Share your thoughts in the comments space below!