We all hate spam comments and comments which are just posted for links. Many of the spam comments contain lots of HTML tags. Luckily the built-in plugin named as Akismet easily does the job of filtering spam comments from the legitimate ones. But it does not stop HTML code in comments section. Its a good idea to disable posting of HTML from your WordPress comments. In this tutorial, you’ll learn how to disable HTML tags in your WordPress comments.
This tutorial will disable active HTML tags only. It won’t prevent posting of escape tags in HTML for e.g. <a>
If someone posts the HTML tags in this way then it will show up but the tags will not function. For e.g. if someone posts the anchor tag, then it won’t be functional.
Diable HTML in WordPress Comments
Before going further, take a backup of your functions.php file so that just in case if anything goes wrong, you can upload the original copy of this file. Now open your functions.php file and add the following code to this file:
// This will occur when the comment is posted function plc_comment_post( $incoming_comment ) { // convert everything in a comment to display literally $incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']); // the one exception is single quotes, which cannot be #039; because WordPress marks it as spam $incoming_comment['comment_content'] = str_replace( "'", '&amp;amp;amp;amp;amp;amp;apos;', $incoming_comment['comment_content'] ); return( $incoming_comment ); } // This will occur before a comment is displayed function plc_comment_display( $comment_to_display ) { // Put the single quotes back in $comment_to_display = str_replace( '&amp;amp;amp;amp;amp;amp;apos;', "'", $comment_to_display ); return $comment_to_display; } add_filter( 'preprocess_comment', 'plc_comment_post', '', 1 ); add_filter( 'comment_text', 'plc_comment_display', '', 1 ); add_filter( 'comment_text_rss', 'plc_comment_display', '', 1 ); add_filter( 'comment_excerpt', 'plc_comment_display', '', 1 ); // Stops WordPress from trying to automatically make hyperlinks on text: remove_filter( 'comment_text', 'make_clickable', 9 );
The official WordPress Codex shows a different way to do this for which you require to edit a core file from wp-includes/kses.php. But its not recommended to edit a core file, because when you update WordPress installation, you’ll need to edit that file again.
Thus, in this above mentioned method you don’t need to edit any core file of WordPress. You simply need to add the above code in your functions.php file and voila, your job is done. No more nasty comments with a dozen of links in it.
Good to see you link to the original source of the code.
Yes, if I have not developed the code, then I would definitely like to give credit to those who have developed it