diTii.com Digital News Hub

Sign up with your email address to be the first to know about latest news and more.

I agree to have my personal information transfered to MailChimp (more information)

Dec272009

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, 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>/ims',
  create_function(
    '$matches',
    '$matches[1] = preg_replace(
        array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "",
        $matches[1]);
      return "" . htmlentities($matches[1]) . "";'
  ),
  $source);

  if ($encoded)
    return $encoded;
  else
    return $source;
}
Share This Story, Choose Your Platform!