Improved Handling of Code in WordPress Blogs with Pre tag

One of the issues I’ve had with WordPress since the beginning is the way it handled code in my posts. Since I like to share code that I come up with, it is annoying when I post code and it gets mangled by WordPress. It would parse it or half-heartedly format it properly. I tried using a plugin, but then I couldn’t use it because it would conflict with my bbcode plugin. Since I had a lot of bbcode in my posts, I had to keep the bbcode plugin and sacrifice the code plugin.

In version 2.1, WordPress handled the <code> tag better, but for some inexplicable reason, would format a portion of the code and then leave the rest improperly formatted, even though the html entities had been converted by WordPress already. I then found WordPress documentation on Writing Code in Your Post .

It turned out that the trick is to use <pre> tags to surround the code.

Here’s what to do:

1. Copy and paste the code into Visual/WYSIWYG view when editing a post. The reason for using this view to paste the code is that it will automatically convert the html entities.

2. Switch to Code view and put <pre> </pre> tags around the code section.

Benefits of this is that whitespace is preserved so that indentation doesn’t get lost; html code tags like img and a don’t get parsed; and the entire code section is properly formatted. Speaking of formatting, it’s possible to stylize the code section by defining pre in the theme’s style.css file.

<html>
	<head>
		<title>Hello World</title>
	</head>

	<body>
		Lorem Ipsum
	</body>
</html>

<code> is still handy for inline formatting of code within regular text, as the beginning of this sentence demonstrates.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>