Please Donate: The Leukemia & Lymphoma Society - Scenic Shore 150 Bike Tour [Donate Here]

Colorizing Code in Wordpress

October 1st, 2006

Last week I had an exchange with Geoff over code formatting in a blog and suggested it could be done with Javascript. We both happen to run Wordpress for our blogs and I have also been looking for a way to insert stylized code into blog entries, so I helped him to put together a solution. Pretty soon we had a solution. Initially I suggested that it could be done with a bit of Javascript. He considered creating his own new script, but like any pragmatic developer, he looked and found an existing solution called dp.SyntaxHighlighter instead of starting from scratch.

To get the dp.SyntaxHighlighter working with Wordpress you have to handle a couple of details. First, assuming you have turned off the WYSIWYG edit mode, Wordpress adjusts your text by encoding certain characters (such as &, < and >) before sending it to the web browser. Second, Wordpress places break tags (<br />) at the end of each line. But Wordpress does have support to get around these details.

To format code dp.SyntaxHighlighter looks for content held inside a specifically marked TEXTAREA tag. The way to prevent Wordpress from encoding your text and placing break tags inside the code block is to place PRE tags around it. Next, you need to call the HighlightAll method to stylize your code.

I attempted to place the call to HighlightAll in the blog entry but that was not working, so I simply placed it in the footer template for my current Wordpress theme. I then placed the following code in a blog entry:

The PRE tag is for the sake of Wordpress. I added the FORM tag even though the dp.SyntaxHighlighter documentation did not request it because I have experienced issues in the past when form elements are not placed within a FORM tag. It does not prevent it from working in Firefox or MSIE and may potentially allow it to work in a wider range of browsers which I have not tested, such as Safari or Opera. Finally, the TEXTAREA is marked with the name and class attributes.

Finally, to color the page you must reference the CSS provided with the dp.SyntaxHighlighter. I put the reference in the header template. You can easily change the CSS to suit your preferences. Once that is in place you should be seeing colorized code in your blog entries.

I was pretty excited about getting this to work, so I dropped a note to Geoff and another developer who posts lot of code on his blog, Scott Guthrie. He replied and explained that he uses CodeColorizer. It is a windows utility so I doubt that Geoff will be using it on his MacBook, but is something .NET developers can readily use.

One Response to “Colorizing Code in Wordpress”

  1. Kevin Says:

    For server-side coloring, I'd recommend taking a look at colorer.

    The client-side javascript solution is interesting, but I don't think I'd use it, personally.