Like the blog? Get the book »

Displaying Code Snippets on a WordPress Site

Displaying Code Snippets on a WordPress Site

Technically, there is nothing special about showing code on a WordPress site. You just wrap code in <pre> (and probably <code>, for semantics and font control) tags, something like this:

<pre><code>
.example {
 
     ..whatever..
 
}
</code></pre>

Then you style up the code with CSS like you would any other element. Perhaps you set your code in your favorite monospace font (not required, but keeps indentation nice) and set off your pre tags visually with a dark background.

code {
   font: 13px Monaco;
}
pre {
   background: #333;
   color: white;
   padding: 20px;
   margin: 0 0 20px 0; /* Probably the same as paragraphs */
}

Remember that <code> tags are “inline”, so you can display a bit of code right within a sentence (like I just did there). <pre> tags are “block” and are used for displaying, literally, blocks of code. Actually, <pre> is just for “preformatted” text, not specifically code, but it preserves whitespace so it’s ideal for code.

Escaping Code

If you are posting HTML code, you’ll need to “escape” it. Particularly the < characters, or else it will be interpreted as a real HTML tag and attempt to be rendered as such. My favorite little one-page-app for this is Postable by Elliot Swan. Just paste some HTML (or whatever) in there and hit the button and it will turn it into all the gibberish (escaped characters) you need to safely post that code and have it look as you intend.

I didn’t like having to go through that whole escaping HTML song and dance on CSS-Tricks so I use the Code Markup plugin instead. It’s super old but it works great. We use it here on DigWP too (see update box, below). Essentially, you just don’t have to worry about escaping HTML for anything within <code> tags. If you want particular tags to be rendered (say, you want to use a <strong> tag to highlight a particular line of code) you can use <code markup="strong">. If you want to absolutely ensure nothing inside is rendered (sometimes it has issues with HTML comments) you can use <code markup="none">.

Update! Check out the much newer and better Prismatic plugin for code escaping and optional syntax highlighting. We use it here at DigWP.com for all code snippets!

Syntax Highlighting

There are a bunch of plugins for this. If you want to go that route, check out this SpeckyBoy roundup post. On CSS-Tricks I do it slightly more manually…

My favorite syntax highlighting helper is google-code-prettify. It’s JavaScript based and library-agnostic so it should work on any site. All it does is wrap <span>s with particular classes around bits of code. Then you use CSS to colorize those classes. They have a variety of themes that come with the download, so you just pick your favorite and include that in your main stylesheet. Here is an example:

Example of google-code-prettifyExample of some code syntax-highlighted with google-code-prettify

Being Good With Scripts

I use a number of scripts on CSS-Tricks: Prettify, a custom version of Modernizer, Respond.js, and FitVids.js. Loading all of those separately would be rather dumb, and an easily fixable performance problem. I just squish (minify and combine, CodeKit can do this for you) all of them together into a file I call fitspondernizerfy.js and load that up in the head of my document (header.php). Normally you don’t load scripts in the head like that, but most of these particular scripts actually should be loaded in the head.

Then at the bottom of the document (footer.php) I load up my custom script where I call the plugin functions. To kick off the code highlighting, I just make sure all the pre tags have the proper class for prettify (using jQuery) and then call the function:

$("pre").addClass("prettyprint");
prettyPrint();

I’m a fan of doing it this way. Many of the other syntax highlighters have more features but I find most of it distracting, ugly, and bad UX. And most importantly, you’re keeping HTTP Requests down by combining scripts.

14 responses

  1. Alex Rodrigues

    Thanks for that Chris. I think i’ll remove the plugin I have and do it this way!

  2. Neat!

    Why doesn’t the built-in editor syntax-highlight code when editing template files? Any way of making it do so? I would hope this is on Automattic’s to-do list if not.

  3. I just embed a gist, thanks to this oembed code snippet.

  4. Even the plugins don’t always work as it can depend on the theme you are using.

    Been looking for a solution like this which i’ll try out.

    I’m using SyntaxHighlighter Evolved plugin for this but still have problems.

  5. fitspondernizerfy.js is the best name ever. I need to start naming my minified CSS and JS this way :) Great article too by the way.

  6. @Chris… Following up on your statement that you’ve copied all your scripts into fitspondernizerfy.js – I notice that CSS-Tricks (version 9) does not use that file and uses fitspondernizer.js instead and loads a 2012 version of “prettify” as a separate download. I only ask because I’m wondering if you found a problem with compatability in the 2012 version requiring its separation – or if you just haven’t gotten around to updating “tricks” yet since this article?

  7. David Hucklesby

    Markdown works well for converting code. I am on a Mac, and use the Mou app to write complete articles. It has a “live” HTML preview alongside my Markdown text.

  8. Thanks for this post Chris a lot of nice addition to the way I handle code, I especialy liked Google Code Prettify ’cause it allows you to create a consistent theme for code aligned with the visual style of a site. I’d like to see an adaptation to responsive design of a script you posted some time ago that on hover extended a code block with jQuery .animate() when the code extended beyond a fixed width of the main column. A final question, do you know of any app to combine and minify for Win? Thanks.

  9. Hi, how do we display a sample shortcode on a wp site..?

    i have a plugin for shortcodes and want to display the shortcodes on the site as samples so that people can easily copy and paste..

  10. yeah that’s one way to do it..

  11. Once I tried to put code into one of my posts but it did not work out. The solution is here :) Also I would like to underline the inline property of “code” tag because it may cause displaying problems.

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace