Grow your CSS skills. Land your dream job.

Posting Code Blocks on a WordPress Site

Published by Chris Coyier

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 spacing. "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. To post a block of code in Markdown, you'll need to indent that code four spaces on every single like, 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, not attempt to be rendered by the browser.

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;

<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.

GitHub is a big user of Markdown, and they solved this issue by adding the triple-backtick style of code blocks, like this:

```
<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.

Beyond that, GitHub-flavored Markdown allows you to specify the language right in the Markdown syntax. So our example could be:

<pre rel="Markdown"><code markup="tt" class="language-markup">```html

I'm some code.

```

Which gives:

<div class="highlight highlight-html">
  <pre>
     <span class="nt">&lt;div&gt;</span>
     hi
     <span class="nt">&lt;/div&gt;</span>
  </pre>
</div>

I'm not sure why it skips the <code> tag and it looks like it does the syntax highlighting server-side with those spans. Just be aware of all that I suppose.

I was able to find wp-gfm which is a GitHub-flavored Markdown plugin for WordPress.

If you go no-Markdown, you'll need to escape the code.

CSS rarely needs 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-escaped 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 data-lang="HTML"><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.

The data-lang attribute on the <pre> tag isn't required, but I might use that in CSS to style the look (and label) the code as HTML. The markup attribute you see in there relates to the escaping plugin. By default it still renders things like <span> and <a> elements, but if you use that attribute with an element-as-value that you don't really plan to use, it will escape those too.

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?

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.

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 some CSS (complete with a demo) that I'm embedding into this post:

* {
  @include box-sizing(border-box); 
}

section {
  background: #eee;
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  overflow: hidden;
}

.module {
  width: 48%;
  min-height: 200px;
  background: white;
  position: relative;
  float: left;
  padding: 20px;
  margin-right: 4%;
  margin-bottom: 4%;
  &amp;:nth-child(even) {
    margin-right: 0;
  }
  box-shadow: 0 1px 3px rgba(black, 0.2);
}

body {
  background: url(http://s.cdpn.io/3/blurry-blue.jpg);
  background-size: cover;
  padding: 30px;
}
 
.come-in {
  transform: translateY(150px);
  animation: come-in 0.8s ease forwards;
}
.come-in:nth-child(odd) {
  animation-duration: 0.6s;
}
.already-visible {
  transform: translateY(0);
  animation: none;
}

@keyframes come-in {
  to { transform: translateY(0); }
}

See the Pen Slide in from bottom boxes by Chris Coyier (@chriscoyier) 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. Plus, if you choose, we embed the code of your choice right in there so in the case JavaScript doesn't run (e.g. an RSS reader) the code will still be present in semantic tags.

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. Although I often just plop code directly into posts as well.


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

Comments

  1. Nice post, Chris. Just a note, Jetpack’s markdown module is also Github flavored, so you can use backticks to wrap code in them. Here’s the original post of Markdown support for WordPress.com . It’s the same module Jetpack uses.

  2. Permalink to comment#

    I’m using Crayon at present on my site but I do worry slightly at the amount of JS/CSS it’s plonking in. It also does the removal of <code> tags which irks me somewhat.

    @briankrosgard – that’s great info, didn’t know about Jetpack doing the GitHub flavoured MD, very useful :)

    • Permalink to comment#

      Same herre, I just started (again) with a new blog and i’m also using Crayon. Although I like the look it’s also a complete overkill in functionality and options. I think I’ll switch to something more lightweight soon while I still can do so easy.

    • Permalink to comment#

      If you guys are looking for a lightweight, nicely designed plugin for code snippets, check out my plugin: http://wordpress.org/plugins/jsj-code-highlight/.

      It basically follows the same workflow specified in the post and uses jQuery to add some divs.

      I wrote it after realizing that all WordPress plugins for code are (IMO) not very good!

  3. Couldn’t have come at a better time. I have been wanting to know more about this for a long time. Thank you SO much for sharing this Chris!

  4. Another solution is to use the custom meta fields. You can use plugins like Simple Fields or Advanced Custom Fields for creating your “code containers”. Then you insert them with a shortcode in your post. A very clean solution.

  5. Permalink to comment#

    I was just looking for a good syntax highlighting solution, seems that Prism by Lea will do the job. Thank you Chris :)

  6. I literally tweeted this question to you yesterday :) It took me a little while but I was able to see that you’re using prismjs on your site. I’m in the process of writing a plugin for this right now (the existing prism plugins aren’t that good).

    Thank you so much for sharing though!

  7. Hi chris nice post, i have a question that is somehow related, how to escape HTML and JS code like on CodePen, do you only use sanitize_text_field? can please give a clear answer, thanks

  8. Nate Wiley
    Permalink to comment#

    Hey Chris,
    Great post.
    I actually was wanting to ask you what you were using on this blog for syntax highlighting. I ended up using prettify in a project I was working on. One thing that I didn’t like about prettify is you’re limited in styling, and some of the code didn’t highlight correctly.. I’m checking out prism now, thanks for the tip!

  9. Hi Chris, I am a regular visitor of css-tricks and now it’s time to appreciate your efforts in web development. Really thanks for helping youngsters like me … once again thanks and keep the good work coming.

  10. Nice article! Just wanted to let you know that you may have forgotten to close the <code> and <pre> tags in one of your code blocks (the one following “That Markdown example above will be turned into this before it hits the browser:”).

  11. A few months ago I shifted from manual code extracts (one for HTML, one for CS, one for JavaScript) and now just use Codepen embeds for everything. So much easier. Love the options for styling it to fit with the site too. Great job!

  12. Permalink to comment#

    I’m not sure if I do the right thing, but this is what I do on my blog:

    <code class="js">
    $(this).attr("data_is","a_code_block");
    </code>
    

    For inline code:

    ...jQuery uses the <code class="inline">$()</code> or <code class="inline">jQuery()</code> function for most of its work....
    

    To escape HTML, I usually copy-paste the code block in a text editor, press Ctrl+H (find and replace), and replace all <s with &lt;, same for > (to &gt;) and & (to &amp;).

  13. When displaying demos and code in blog posts (that can be used or don’t harm the flow of the content) you should wrap the <pre><code>...</code></pre> into a <figure> (with an optional <figcaption>).

    http://www.w3.org/TR/html5/grouping-content.html#the-figure-element

  14. Permalink to comment#

    We just started using CodePens on our blog, before I found out about your new WP plugin we created our own shortcode. Each developer has a codepen profile attached to their user account so the shortcode can simply take the slug:

    [codepen slug="MYSLUG"]
    

    Shortcode PHP excerpt:

    return
        '<p data-height="'.$height.'" data-theme-id="'.CODEPEN_THEME_ID.'" data-slug-hash="'.$slug.'" data-default-tab="result" class="codepen">See the Pen
            <a href="http://codepen.io/'.$codepen_username.'/pen/'.$slug.'">'.$slug.'</a>
             by '.$user_name.' (<a href="http://codepen.io/'.$user.'">@'.$slug.'</a>) on
            <a href="http://codepen.io">CodePen</a>.
        </p>'.
        ($script_already_included ? '' : '<script async src="//codepen.io/assets/embed/ei.js"></script>');
    

    We threw in some other optional parameters for height and selecting another user other than the post author.

    This makes sure we always keep the same codepen theme across our site. What would be great for codepen would be some type of organization accounts or a more upfront way of creating and saving themes but this currently works great for us.

  15. Permalink to comment#

    I use Prism, but have a problem where blank lines are removed from my sample Javascript.

    Any ideas?

  16. Permalink to comment#

    Crowd Favorite’s Capsule theme is a neat front-end Github-flavored Markdown editor.

    I recently installed it to replace the functionality of Gistbox (via Gists) and Pastebin. So I have my own hosted code snippet library, e.g. code.damoncook.net

    Bonus, you can set up Capsule Server to have a team collaboration synced snippet library.

  17. Permalink to comment#

    After quite a bit of testing and research I settled on using the SyntaxHighlighter Evolved plugin for WordPress. It allows you to wrap your code inside [php][/php] tags which is nice and clean in the back end.

    It works pretty nice on http://www.epicwebs.co.uk.

  18. Permalink to comment#

    You can also just post a Gist and be done with it :)

    • Sure, which can be great. Be remember people subscribed to your RSS feed (WordPress automatically creates feeds for you, one reason you might be using WordPress to begin with) won’t see anything.

  19. Nour Akalay
    Permalink to comment#

    Hello,
    I tried all your markdown suggestion and I found out that the only one that plays nice with prism and wp-gfm was markdown-quicktags.
    I tought I’d let you know

  20. Just the problem I’ve been trying to solve. Thanks!

  21. thanks chris for simplifying wordpress codes usage.

  22. Permalink to comment#

    I do not have a wordpress blog. Is there another standard highlighter plugin I can use on my own CMS? There are so many options for standalone code highlighters and I am still researching which would be the best one. Thanks!

  23. Too much information for me.. I am looking for a smiple solution to add HTML codes to my posts.
    I tried Postable. it works well but it’s tedious to use it everytime, as you said.
    Thanks

  24. Mayhem

    Or you could use the recommended methods

    http://en.support.wordpress.com/code/posting-source-code/

    • That’s for WordPress.com, with just a passing mention of a plugin at the bottom. This covers that, and a bunch of other considerations you might want to think about for a self-hosted WordPress blog.

  25. Thank you for showing the exact way to use Pre Tag within WordPress Editor. I will give it a try and hope it works. :)

  26. MArk

    Hi,
    nice article, but I have problem with displaying in <pre> or <code>. It’s everytime show the input and destroys rest of the code.

    Where is the problem?

    Thanks

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".