how to use code syntax highlighter in wordpress

how to use code syntax highlighter in wordpress

One of the thing that you absolutely need for a technical blog is to have some kind of syntax highlighter to make code examples easy to read.

When i started this blog, in my first blog itself i started missing syntax highlighter.

I started to search for one. Following was my selection criteria:

  • Has to support multiple languages
  • Should be easy to setup
  • Should be easy for me to highlight code with just css class

I tried to install a few wordpress plugin but none worked per my expectation.

So i started to search for highlighter which does not have to be a wordpress plugin and i found highlight.js which looked promising And it worked perfectly fine when i tried it for few languages:

  • YAML
  • Dockerfile
  • Go lang

For embedding this with my WordPress installation i had to modify header.php file as follows:

<link rel="stylesheet" href="https://rajatjindal.com/highlight-js/styles/default.css">
<script src="https://rajatjindal.com/highlight-js/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

Once i did this, highlighting code was as easy as follows:

<pre><code class="yaml">---
kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: k8s-awesome-service</code></pre>

which will be displayed as follows:

---
kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: k8s-awesome-service

I do plan to use this extensively for other programming languages as i learn and write more.

I will update the post after a few weeks as i use it more

Leave a Reply

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