Of Zen and Computing

How to Include Source Code in a WordPress Blog Post

Thursday, December 13, 2007
The WordPress logo

Lately, you may have noticed articles like “How to Code a PHP Contact Form” contain source code examples for various programming tasks, and let me tell you, it was a real pain getting WordPress to cooperate with that code. By using these notes, you will hopefully spend a lot less time trudging through the muck than I did.

WordPress runs the text of blog posts through a number of filters in order to display it properly in a Web browser. Since source code differs greatly from the written word, these filters posed a number of problems for source code inside a blog post. In order to display the code correctly, I used a number of Wordpress plug-ins to alter the way in which WordPress treats text.

Stop HTML Special Character Replacement

There are many characters inside source code that should not be converted to their corresponding HTML entities. I would rather single quotes, double quotes, and other such entities remain untouched, and so I used Code Autoescape by Priyadi Iman Nurcahyo to keep WordPress’ formatting functions at bay.

I did, however, continue to use the proper HTML entities to display < and >.

Stop WordPress from Formatting Text Blocks

WordPress does a pretty good job of formatting blocks of text with paragraph tags and line breaks. Unfortunately, these things have no place in code. I found it particularly irritating when WordPress would insist on enclosing <pre> tags within paragraph (<p>) tags. I was able to modify this behavior with the Text Control plug-in by Jeff Minard.

Syntax Highlighting

With text formatting under control, the last piece of the puzzle was the fun part: syntax highlighting. Syntax Highlighter by Alex Gorbatchev was the most impressive and aesthetic utility I came across, by far. Alex’s Syntax Highlighter has a number of benefits:

  • It is written entirely in JavaScript, and formats code on-the-fly. This means my code does not get wrapped in a sea of HTML tags and inline CSS rules.
  • Line numbers are generated on-the-fly.
  • The visitor can easily print the code, or copy it to the clipboard in one click.

In order to respect clients who cannot or do not execute JavaScript, I include a <noscript> tag before the first block of code in each post, stating that syntax highlighting is present and requires JavaScript.

File under: Code

Digg icon StumbleUpon icon del.icio.us icon Facebook icon

Other articles related to this page

© 2006-2008 OfZenAndComputing.com
E-mail Disclaimer | Terms of Service & Disclaimer | Sitemap

Subscription Options
Search Our Archive of How-To Articles and Blog Posts