Convert Pre Tag Contents to HTML Entities in WordPress.
by c.bavota | 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.



Thanks for sharing. I’m an upcoming webdeveloper and I enjoy your posts but I still have a lot to learn
Nice article! For non-programmers, http://www.html-entities.org is a nice tool.
Thanks for sharing – I like your blog very much
It works perfect, thanks man!
It seems to work a treat, thanks for sharing. Gridiculous is a classy looking theme by the way.
This is an absolute life saver, I’ve been having a nightmare trying to put together a simple tutorial on WordPress because of the semi-auto-conversion of some HTML elements.
Your function worked a treat.
Thanks,
David
Thanks for sharing. I’m an upcoming webdeveloper and I enjoy your posts but I still have a lot to learn
I am using this function to my site
Thanks for sharing. It works perfect
Thanks for sharing. I’m an upcoming webdeveloper and I enjoy your posts but I still have a lot to learn!
Thanks…
Awesome site you have here but I was wanting to know if you knew of any discussion boards that cover the same topics talked about here? I’d really love to be a part of community where I can get comments from other experienced individuals that share the same interest. If you have any suggestions, please let me know. Kudos!
nice work buddy. thanks
Thanks for sharing. It works perfect
Thank you very much. Great Post – helps perfect for my problem
Dean, thanks fot the url http://www.html-entities.org/ … I browse to find this characters from time to time and this page has it all in one place.
totally useful !
Yeah very much tutorial, thanks for sharing.