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.

1 Comment

  1. Jan-Philip Gehrcke

    Hey. Thanks for your post and for writing nice words about WP-GeSHi-Highlight. I have just released a new version with new language support and discovered your blog post while researching who/what is using WP-GeSHi-Highlight as of today.

    I agree that the whole escaping dance is tedious. That’s a tough problem to solve, unfortunately.

    Also the fact that switching between the editors can mangle your data is super annoying, I get it. But I have so far not found a *reliable* way to mitigate that. There are hacks out there in the world and people that claim to have solved this. But to date I was not able to gain the confidence that the corresponding “hacks” or “workarounds” don’t actually break some other workflow, or other plugins.

    Cheers and thanks!



Leave a Comment

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