Easy way to post code with syntax highlighting in WordPress

Most solutions I found to post code snippets in a WordPress article with syntax highlighting either use Markdown, disable the visual editor or use WordPress plugins. Others suggest using an online Pastebin, Codepen or similar. But these solutions can get tedious if you post lots of small snippets of code, they disable functionality, or add lots of code you don’t really need.

So here’s an easier way to do this!

Step 1

Find a syntax highlighter you like. I’m using Google Code Prettify. To add it to your WordPress site, just add this code in the <head> of your theme.

<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>

Step 2

Open your WordPress post, switch to Text view and paste this code where you want your code to show up on the page.

<pre class='prettyprint'>

Step 3

Switch back to the Visual editor and paste your code snippet after selecting the word “code”. This word was added just so you can easier target the pre code block.

Done! By pasting the code in Visual view, you don’t have to worry about escaping the code since WordPress does that automatically. You can easily switch back and forward between the Visual and Text views without any issues.

Bonus: styling

The default styling of the pre box is quite barebones. Here’s how to give it some styling and make the lines wrap.

pre.prettyprint {
  margin: 3em 0;
  padding: 2em;
  border-color: #f5f5f5;
  border-radius: 6px;
  background-color: #fff;
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 130%;