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 <)
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
<code>...</code>is encoded. - Line breaks after opening
<code>and before closing</code>are removed in order to avoid unnecessary<br />tags.
Awesome, thanks for the code :)
It’s annoying having to recode everything just to post it on someone else’s site.
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.
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.
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.
The plugin is now available in the repository:
http://wordpress.org/extend/pl.....-comments/
Great work, Ryan! Thanks.
You should use esc_html() as the way you are using wp_specialchars() is vulnerable