Many blog authors use plugins in WordPress to make their code samples look good. Code is generally written in most IDEs in a mono-spaced font, yet blogs are written in proportional fonts so code pasted in between blog text is usually very unreadable until you add a plugin to wrap the code samples in a mono-spaced font style.

There are a great deal of plugins available for WordPress which will make your code samples look good and the one I’ve started to use is called “Prettify GC Syntax Highlighter” (It had the highest rating!) The style is great but you can’t easily add captions to the code.

The Prettify plugin allows us to wrap the code we want to add into the blog post in a PRE tag with some class identifiers which the plugin picks up.

Adding a <DIV> with a specific style every time I add code to my blog post is something I’ll forget and I’ll end up having to open an old post to remember how I did it. That then becomes an arduous task and I’ll end up not posting a blog about something cool, so I had to come up with a better way.

CSS 2.1 introduced the :before and :after pseudo-elements for style sheets, we’re also able to pull attribute values from the parent element. This allows us to easily grab data and put it into a <DIV> after the <PRE> tag.

So, when we put the PRE tag into the blog post we add a CAPTION attribute, like so:

<pre class="prettyprint lang-HTML" caption="Your caption text goes here">

Then we add the CSS to the blog, as of WordPress 3.0 we can do that via the “Appearance > Edit CSS” menu option. Copy and paste the code below, then amend to make your caption blocks look how you want them.

pre.prettyprint:after {
	float: right;
	border: 1px solid #ccc;
	border-radius: 3px;
	background: #ddd;
	padding: 10px;
	content: attr(caption);

The content element pulls the value of the “caption” attribute in as the HTML text for the new DIV.

We already use the :after and :before psuedo-elements on the blog. The easiest way to add the subtitle onto the header was to do it via CSS rather than add a DIV tag, and add a CSS ID with more styling. Using the BEFORE psuedo-element we can add content directly into the DOM.

#site-title:before {
	margin-top: 10px;
	float: right;
	color: #999;
	font-size: .8em;
	content: "// Code, Events, Games & Tech ";

One thought on “Add Captions to WordPress Prettified Code

  1. This is an excellent tip. Thanks Phil. I have one suggestion. The WP editor strips out most attributes from pre (and other) tags to avoid cross-site scripting attacks. However it allows the “title” attribute. So I was able to use your approach, replacing “caption”, with “title” in the pre tag.

Leave a Reply