Convert Pre Tag Contents to HTML Entities in WordPress.
by Bandicoot Marketing on | Posted in Tutorials | 19 comments
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( '|<pre.*>(.*)</pre|isU' , 'convert_pre_entities', $content ); } function convert_pre_entities( $matches ) { return str_replace( $matches[1], htmlentities( $matches[1] ), $matches[0] ); }
Now all your code within a PRE tag will be converted automatically and displayed properly on your site.
19 comments for “Convert Pre Tag Contents to HTML Entities in WordPress.”