Displaying Code in WordPress with Markdown and Code Prettify

Occam’s Razor is the precept that — all things being equal — the simplest explanation tends to be the correct one.

There are many ways to incorporate the entry and display of code elements within WordPress. But as with most things software, the solutions we like best are the ones with the fewest moving parts and least amount of hassle. With that in mind, we searched for the simplest way to configure WordPress to accept code during post editing and to display it with appropriate syntax highlighting.

Step 1: enable Markdown within Jetpack tools. Jetpack is a suite of common tools/plugins that take the rough edges off a default WordPress install. There’s a very good chance it will already be installed in your WordPress site by default. Markdown is a syntax language with a minimal learning curve that lets users construct sophisticated HTML posts using only common text-based characters. For our purposes it allows large quantities of HTML or javascript code to be entered without all the painful character escaping.

Step 2: install the WP Code Prettify plugin. This plugin will add Google’s Code Prettify syntax highlighting tool to your site. Code Prettify is a minimally sized JS library (with optional CSS) that takes any <pre> or <code> tags with the prettyprint class and applies auto-detected syntax highlighting. It really is that easy.

Step 3: sling some code! Code placed between the ~~~ (triple tilde) Markdown-respected characters will be wrapped by Markdown in a <pre><code></code></pre> block. So

~~~
<div><strong>This is some engaging content</strong></div>
~~~

renders as

<div><strong>This is some engaging content</strong></div>

Notice how the input code is not encoded with &lt;‘s and &gt;‘s and whatnots. Nice.

Step 4: Now, for syntax highlighting, add a class to the Markdown-rendered <code> block thusly:

~~~prettyprint
<div><strong>This is some engaging content</strong></div>
~~~

then displays as

<div><strong>This is some engaging content</strong></div>

Step 5 (optional): To add the multiple class names required for numbering lines (“linenums”) or specifying the code language (“lang-xyz”), use curly brackets like this:

~~~{.prettyprint .linenums}
<div><strong>This is some engaging content</strong></div>
~~~

then displays as

<div><strong>This is some engaging content</strong></div>

Summary: There are other more full-featured code entry and syntax highlighting WordPress solutions out there, but this one is short, sweet, and to the point.

Posted in: