---
title: Automatically Escape HTML Entities of Code Fragments in Comments
date: 2009-12-26T03:51:52+00:00
modified: 2012-08-23T10:57:02+00:00
permalink: https://kaspars.net/blog/automatically-escape-html-entities-of-code-fragments-in-comments
post_type: post
author:
  name: Kaspars
  avatar: https://reverse.kaspars.net/gravatar/avatar/92bfcd3a8c3a21a033a6484d32c25a40b113ec6891f674336081513d5c98ef76?s=96&d=mm&r=g
post_tag:
  - Snippet
category:
  - WordPress
---

# Automatically Escape HTML Entities of Code Fragments in Comments

**Update**: *[Ryan](http://ryanhellyer.net/) has made this into a plugin — [Code Comments](http://pixopoint.com/code-comments/)*.

Add this to your theme’s `functions.php` to allow readers post fragments of code in their comments (wrapped in `...`) 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>" . esc_html( $matches[1] ) . "</code>";'
  ),
  $source);

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

### Worth noting:

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