Adding code to wordpress posts, especially if you, like me, use the HTML editor to write your posts, requires that you use HTML escape codes for changing every ‘>’ character into ‘>’ and so on and so forth as described in the wordpress codex.
Several solution are there including plugins that do more than just displaying the code but go beyond that towards formatting it as well. I have switched to using the google-code-prettify and therefore I needed a simple solution to just escape the HTML in <pre> HTML elements.
Therefore, I have put together the following piece of code that can be easily added to the template functions.php file to achieve that simple task.
function skinju_escape_pre ($content)
{
$pieces = preg_split ( '/(<pre.*>.*?<\/pre>)/si', $content, -1, PREG_SPLIT_DELIM_CAPTURE );
$procesed_content = '';
foreach ($pieces as $piece)
{
if ( preg_match ( '/(?P<opening><pre.*>)(?P<content>.*)(?P<closing><\/pre>)/imxsU', $piece, $matches ))
{
$matches['content'] = str_replace ( '&', '&', $matches['content']);
$matches['content'] = str_replace ( '<', '<', $matches['content']);
$matches['content'] = str_replace ( '>', '>', $matches['content']);
$matches['content'] = str_replace ( '"', '"', $matches['content']);
$matches['content'] = str_replace ( '\'', ''', $matches['content']);
$procesed_content .= $matches['opening'] . $matches['content'] . $matches['closing'] ;
}
else
{
$procesed_content .= $piece;
}
}
return ( $procesed_content );
}
add_filter('the_content', 'skinju_escape_pre', 10);

Comments
How would we add this to
tags as well?wait – why cant you just use htmlspecialchars or wp_specialchars?
just noted your comment system striped the <code>> out of my last comment – you could always add
add_filter(‘comment_text’, ‘_escape_pre’, 10); to add your magic to comments as well.