Wordpress Code Formatting

September 25, 2006 - 2 minute read -
WordPress code formatting blogging

I finally got tired of dealing with reformatting that Wordpress does in its attempt to be "user friendly". In general it does the right thing, but when you deal with code snipits inside <code> tags a lot it can quickly become a problem.

I wanted to accomplish two things

  1. Have whitespace matter
  2. Not have Wordpress add extra linebreaks or evaluate my >s as HTML

1. Is easily done with CSS

code {
    white-space: pre;

This CSS will render the text including showing the spaces and line-breaks however they are in the source. This is just the right things for code.

2. Getting Wordpress to not muck with code blocks

This on the other hand requires coding a solution. Luckily someone has done the hard work for us. There is an existing plugin called Preserve Code Formatting that handles this. Basically it looks through the HTML source of a posting and looks for <code> and
 blocks. When it finds those blocks it removes all of the extra Wordpress formatting and handles escaping HTML entity characters.

The other thing I was running into was that Wordpress was "closing" things that looked like HTML. I ran into this when I was writing code snipits that contained Generics syntax.

I tracked that down to a writing setting in Wordpress. Under Options -> Writing there is a checkbox that says: "WordPress should correct invalidly nested XHTML automatically". When this option is enabled, Wordpress will erroneously see certain things as HTML markup and try to create closing tags.

With this option selected I would get:

<address> addresses;

Instead of the correct output I would get when I unselected the option:

List<Address> addresses;

With the plugin in place, a bit of CSS and turning off one option, I can now copy-and-paste code snipits into Wordpress and not have to deal with formatting.

Next step...syntax highlighting.

Update: The other thing that I found in the functions-formatting.php file there is a method called 'wpautop'. This method has a call to remove breaks from

 tags. So I copied the line and changed it to do the same thing to <code> tags.

$pee = preg_replace('!(<code.*?>)(.*?)</ code>!ise', " stripslashes('$1') . stripslashes(clean_pre('$2'))  . '</ code>' ", $pee);