Displaying Code in a WordPress Post

Writing a WordPress blog post that contains code snippets can be tricky. If you switch back and forth between the visual editor and the text editor, your formatting and even the content can get totally messed up.

There are a lot of WordPress plugins out there that try to help you with code formatting. Most of the ones I found in official WordPress Repository were really out of date.

I settled on WP-GeSHi-Highlight, which was active and up-to-date. It provides syntax highlighting and preserves your code layout.

After installing the plugin, you invoke the plugin by labeling the code snippets in your post. In the WP text editor, add pre tags around your code and insert the following arguments for HTML code.

<pre lang="htmlstrict" escaped="true">

WP-GeSHi-Highlight handles lots of languages. Check the website for all of its options.

The only tedious part is encoding all the special HTML characters. If your code includes < and > — replace them with:

&lt; and &gt;

The escaped argument will translate them back.

I still had to be careful switching between visual and text editors. I lost my nicely formatted code, due to a typo in my pre arguments. Therefore, I find it’s good, no–essential, to prep my posts in a text editor. I can use the WordPress visual editor for formatting at the finish, but I always want to have a backup of any complex layout while I’m editing.

Leave a Comment

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