Posting Code Blocks on a WordPress Site

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

Originally published in February 2014, now updated/corrected/expanded.

So you’ve installed WordPress and want to blog about code. Yay! You’re a hero and I thank on behalf of myself an coders everywhere. Here’s what you’ll need to do and think about to actually get publishing blocks of code.

The HTML for a “code block”

There is an element specifically for code: <code>. I’d say it’s semantically correct to wrap any and all code in it. Browser’s default stylesheets leave it as inline element, and I’d recommend you leave it that way so you can use it within sentences like I did in the last sentence.

But you’ll want to use a block-level element to wrap a block of code. <pre> is the perfect element for that, as it naturally retains whitespace. “Pre” as in “Preformatted text”. Multiple spaces will render as multiple spaces instead of collapsing into a single space as normally happens in HTML. That’s perfect for code, because you’ll likely want to use indentation in a block of code and you don’t want to resort to any &nbsp; shenanigans.

So:

<pre><code>Your 
   
   block
  
       of

   code
 
 here.</​code></​pre>

Turn off the “Visual” editor

By default, WordPress lets you switch between Visual and Text tabs in the editor.

For you, the Visual editor has to go. You will never use it. You want full control of the text you are writing and want it to stay just how you write it when you save it.

Turn it off under Users > Your Profile

Are you going to blog in Markdown or not?

Here on CSS-Tricks I do not, but if I could go back in time to the beginning I probably would. On most subsequent blogs I’ve done, I do use Markdown and prefer it. If you are going to, I’d suggest using Jetpack’s Markdown feature.

To post a block of code in Markdown, one ways is to indent that code four spaces on every single line, like this:

Yadda yadda yadda. I'm a *paragraph* in Markdown. Here's a [link to Google](http://google.com). Here's a block of code:

    <div>
       <p>I'm some code.</p>
    <div>

Another paragraph here.

Manually doing that is going to get old very fast. So you’ll want to replace your editor buttons with Markdown buttons. It looks like the plugin Markdown Quicktags can do that.

What’s cool about using Markdown is that you don’t have to worry about escaping the code. So those angle brackets are no rendering threat, Markdown will escape them for you. In other words, all those angle brackets (<) in the HTML example above will be turned into &lt; and thus display on the screen as an angle bracket rather than confuse the browser into thinking an HTML tag is coming up.

That Markdown example above will be turned into this before it hits the browser:

<p>Yadda yadda yadda. I'm a <em>paragraph</em> in Markdown. Here's a <a href="http://google.com">link to Google</a>. Here's a block of code:</p>

<pre><code>&lt;div&gt;
   &lt;p&gt;I'm some code.&lt;/p&gt;
&lt;div&gt;</code></pre>

<p>Another paragraph here.</p>

If you’re interested in blogging in Markdown, you have some options. Jetpack, the Automattic-created and maintained plugin, now offers it as part of it’s mega-pack of offerings. At the time being I use WP-Markdown here on CSS-Tricks (I know I said I don’t use Markdown, but I do for the Forums and comments, just not blogging).

Two I haven’t personally tried are Typewriter and Markdown on Saved Improved.

There is a fairly major limitation here though. Notice that the four-spacing indentation converts into a <pre><code> block, but there was no opportunity there to add attributes to those tags. Attributes (like classes and data-* attributes) are a common need. You might want to use a syntax highlighter (we’ll talk about those later) that requires some attributes to do it’s thing. Or you might want to identify the code block somehow by language.

More convenient than indenting, many “flavors” of Markdown (including the Jetpack version) support code fencing, which is putting blocks of code within triple backticks:

```
<div>
  <p>I'm some code.</p>
<div>
```

I’d call this straight up better. It’s easier to jump into a code block while writing without having to worry about the indentation thing. Plus code has it’s own indentation going on so it’s nice to start flush-left with that.

You can also specify the language right in the Markdown syntax. So our example could be:

```html
<div>
  <p>I'm some code.</p>
<div>
```

Which gives:

<pre><code class="html">&lt;div&gt;
  &lt;p&gt;I'm some code.&lt;/p&gt;
&lt;div&gt;
</code></pre>

If you DON’T use Markdown, you’ll need to escape the code.

Blocks of CSS code rarely need escaping, but HTML for sure does, and JavaScript sometimes has HTML in it (as well as just about all backend languages), so you might as well just assume you need to escape all code.

You could do it manually by converting all <‘s into &lt;’s, but you’ll go nutty doing that. You could use a tool like Postable to copy-and-paste blocks to be escaped, but that’s slow and tedious too.

I prefer using a plugin called Code Markup for this. It just auto-escapes anything it finds within <code> tags so you just never have to think about it.

Because I use that plugin on this site, I can do stuff like:

<pre data-lang="HTML"><code class="language-markup"><div>
  <p>I'm some code.</p>
<div></​code></​pre>

And it works great. No escaping. Full attribute control.

Handling Syntax Highlighting

Remember that one option for syntax highlighting blocks of code is not syntax highlighting. Certainly that would be the fastest and easiest way. But you might want it. Personally I like it. I like the way it looks. Here’s a few options.

What essentially happens with any syntax highlighter is bits of code end up getting wrapped in <span>s with class names that you colorize with CSS. Choosing is a matter of features.

Prism.js

Here on CSS-Tricks, I use (and recommend) Prism by Lea Verou as it works with those right out of the box. It’s small, fast, and (my favorite) as rational class names for styling. You choose which languages you want it to support as you download it.

I also use that escaping plugin, meaning I don’t need to escape HTML inside code tags, so again that looks like this:

<pre><code markup="tt" class="language-markup"><div>
  <p>I'm some code.</p>
<div></​code></​pre>

That class="language-markup" on the code tag is what Prism picks up on to syntax highlight. It works automatically on all code it finds with that class name pattern by default, but you can use the API instead if you want to do your own thing.

Prettify

An extremely popular one is google-code-prettify. To syntax highlight a block, you put class="prettyprint" on either the code or pre tag.

It’s a larger file size than Prism, but one advantage is that it auto-detects language (and supports a ton of languages), so it should work on just about anything without you having to specify it.

Others

Digging around a little, there are plenty more that I can’t vouch for but seem like they’ll do the trick: Rainbow, SyntaxHighlighter, Chili (jQuery), JSHighlighter, jQuery.Syntax (jQuery), GeSHi, Lighter (MooTools), highlight.js, SHJS, and Pygments (Python).

Deciding

To decide amongst these, you might think about these things:

  • What languages do I mostly need to support?
  • Do I want to show line numbers?
  • Do I need to put links within the code?
  • Do I want to be able to highlight parts of the code or lines?
  • Do I have legacy code blocks I need to support? What format are they in?
  • Is the code easy to copy and paste? Do I want features to help with that?
  • Is client-side syntax highlighting OK or do I want it to happen server-side?

Visually Identifying Code Blocks

I think it’s a nice touch to be able to see at a glance what kind of code a block of code is. On this site, I do that through an attribute on the block itself, then style the value of that attribute as part of the display. You can see it in action in most of the code blocks shown here (assuming you are looking at the site itself, not reading it syndicated elsewhere).

Here’s how you can visually show a particular attribute on the code block (the styling is totally up to you!):

pre[data-language-display]:before {
  content: attr(data-language-display);
}

Dealing with Legacy Code

If you have a bunch of code blocks on a site already, I’d still recommend choosing a syntax highlighter that you like the features of for current and future use. Then finding a way to make it work for the older blocks.

For instance, let’s say I have a legacy code block that is marked up like this:

<pre><code class="javascript">
  var thing = document.getElementById("thing");
</​code></​pre>

That’s not the right class name for Prism. So I might use jQuery to do something like:

$("code.javascript")
  .removeClass("javascript")
  .addClass("language-javascript");

And make sure that JavaScript runs before Prism does. I might also take the opportunity to $.trim() the code because, as written above, there is an extra return at the top and bottom which might affect the styling of the code block.

I mean this just as an example. The overall point is: you can manipulate the legacy code blocks as needed to fit the new format.

Using a Plugin

There are many, many plugins for this. This post is mainly geared toward handling this on your own, as that’s generally the kind of control I like. But I’m sure there are plenty of well done plugins for this. I’m afraid I can’t recommend one, but this is what I’d look for:

  • Good reviews / ratings / looks like it's updated
  • Doesn't make you do anything weird/proprietary with code blocks. For example, use a [shortcode]. This will make you tied to that plugin forever.
  • Supports the languages and features you need (and just the things you need, doesn't load everything under the sun.)

Third Party Help

When creating the Embedded Pens feature on CodePen, we knew that displaying demos and code in blog posts is kind of a pain in the butt, so we set out to make that easier.

Here’s an example of an embedded Pen, defaulting to the CSS code:

See the Pen Dynamic Image Colorizing with by Noah Blon (@noahblon) on CodePen.

I don’t need to worry about syntax highlighting, escaping, or anything, and get the benefit of showing the rendered demo as well.

Many of the other code editor sites offer embedded code as well like JSFiddle and JSBin. GitHub Gists can be useful for this too. Perhaps my favorite reason for using third-party tools for this is that you can go update the demo there and the blog post automatically has the new code. You don’t have to update stuff in two places.


Do you have your own way of handling code blocks on a WordPress site? Do share.