There are plenty of WordPress plugins for syntax highlighting, but the ones I tried (and I tried many) tried to integrate into the editor, letting you edit code with syntax highlighting enabled.

This isn’t what I wanted.

I wanted a syntax highlighter to highlight the code blocks in my blog posts as visitors were reading them.

While I couldn’t find any WordPress plugin that would do this for me, I knew of JavaScript libraries that could get this done such like highlight.js and prism, so I used these to build what I wanted.

Which one did I go with? Both.

Why use both?

Highlight.js and Prism both have their advantages.

Highlight.js has an awesome language auto-detection feature that can accurately detect the language used in a give code block. In then adds a language-xxx class to the code block to identify it, such as language-php.

Prisma, on the other hand, has cleaner looking themes and rich set of plugins for things like line numbers and copying code to the clipboard. It doesn’t support auto-detection though, and I don’t want to manually edit my posts to add the necessary metadata.

I needed the auto-detection from Highlight.js with the themes and plugins from Prism, so I used both.

Give me the code

Here it is.

I first load and run highlight.js to add the necessary language classes to my code blocks. Then I load Prism and the Prism CSS to highlight the code.

1<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script>
2 
3<script>
4 document.addEventListener("DOMContentLoaded", function () {
5 hljs.highlightAll()
6 })
7</script>
8 
9 
10<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/themes/prism.min.css" integrity="sha512-tN7Ec6zAFaVSG3TpNAKtk4DOHNpSwKHxxrsiw4GHKESGPs5njn/0sMCUMl2svV4wo4BK/rCP7juYz+zx+l6oeQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
11 
12<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/components/prism-core.min.js" integrity="sha512-9khQRAUBYEJDCDVP2yw3LRUQvjJ0Pjx0EShmaQjcHa6AXiOv6qHQu9lCAIR8O+/D8FtaCoJ2c0Tf9Xo7hYH01Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
13 
14<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/plugins/autoloader/prism-autoloader.min.js" integrity="sha512-fTl/qcO1VgvKtOMApX2PdZzkziyr2stM65GYPLGuYMnuMm1z2JLJG6XVU7C/mR+E7xBUqCivykuhlzfqxXBXbg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>