Convert Pre Tag Contents to HTML Entities in WordPress.

When I was working on the Gridiculous responsive grid boilerplate and putting together the site, I wanted to create an easy way to add a syntax highlighter for my code snippets. I decided to use the Google Prettify syntax highlighter since it was lightweight and super easy to install. The only problem was actually adding my code snippets to the WordPress code editor, since it would cause some issues on the front end and render some of the HTML tags as opposed to just displaying them as text.
Thankfully, I was able to put together a simple function that would automatically convert all the code within my PRE tag to HTML entities so that it would be displayed properly to users. All you need to do is add the following to your functions.php file:

add_filter( 'the_content', 'pre_content_filter', 0 );
/**
 * Converts pre tag contents to HTML entities
 *
 * This function is attached to the 'the_content' filter hook.
 *
 * @author c.bavota
 */
function pre_content_filter( $content ) {
	return preg_replace_callback( '|(.*)

Now all your code within a PRE tag will be converted automatically and displayed properly on your site.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie