WordPress: Automatically escape HTML entities in Comments

Most bloggers on WordPress, have encountered this problem, when leaving a HTML or PHP code into comments, that Add this to your theme’s functions.php to allow readers post fragments of code in their comments (wrapped in <code>...</code>) which are automatically encoded (think of < and &lt;). Kaspars posted an extremely handy code on his blog, […]

Most bloggers on WordPress, have encountered this problem, when leaving a HTML or PHP code into comments, that Add this to your theme’s functions.php to allow readers post fragments of code in their comments (wrapped in <code>...</code>) which are automatically encoded (think of < and &lt;). Kaspars posted an extremely handy code on his blog, that helps you getting over this problem. Just paste the following code into the functions.php files:

add_filter('pre_comment_content', 'encode_code_in_comment');
function encode_code_in_comment($source) {
$encoded = preg_replace_callback('/<code>(.*?)<\/code>/ims',
create_function(
'$matches',
'$matches[1] = preg_replace(
array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "",
$matches[1]);
return "<code>" . htmlentities($matches[1]) . "";'
),
$source);
if ($encoded)
return $encoded;
else
return $source;
}