Automatically Escape HTML Entities of Code Fragments in Comments

Update: Ryan has made this into a plugin — Code Comments.

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;)

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]) . "</code>";'
  ),
  $source);

  if ($encoded)
    return $encoded;
  else
    return $source;
}

Worth noting:

  • Everything wrapped in <code>...</code> is encoded.
  • Line breaks after opening <code> and before closing </code> are removed in order to avoid unnecessary <br /> tags.

7 Comments

Ryan 7:24

Awesome, thanks for the code :)

It’s annoying having to recode everything just to post it on someone else’s site.

Ryan 9:29

I turned this into a plugin for my own use and figured I may as well make it available for anyone with a use for it … http://pixopoint.com/code-comments/

@Kaspars – if you would like to release a plugin to do this yourself, just let me know and I’ll point visitors to my own blog post over to your site instead of using my version.

Kaspars 15:52

This is awesome, Ryan — thanks for turning it into a plugin. This is the exact reason why I love open source.

The only suggestion I have is that you upload it to the official repository.

Ryan 18:09

Yep, I’ll upload it to the repository :)

I was actually waiting to check that you weren’t planning to do it youself (I didn’t want to step on your toes).

I’ll post back here once it’s uploaded to the repository … which will require me writing a readme.txt file for it first.

Ryan 13:29

The plugin is now available in the repository:
http://wordpress.org/extend/pl.....-comments/

Kaspars 0:28

Great work, Ryan! Thanks.

Feedback on other blogs (trackbacks)

Leave a comment

Note: Basic HTML formatting is allowed. If you post HTML or PHP fragments, wrap them with <code>...</code> which will automatically encode the HTML entities.

About the Author

Kaspars Dambis I am a race car driver, engineer and a web designer living in Latvia and working on the web since 2000. Read more or get in touch.

Es vienmēr tevi mīlēšu, Sirsniņ!