We have received many spamming comments in wordpress. How to filter them? In this tutorial, we will introduce you how to do.
Here is a wordpress spamming comment example.
We will find some features in these comments, we will use these features to filter them.
How to filter wordpress spamming comments?
We will use preprocess_comment hook to implement this function.
apply_filters( 'preprocess_comment', array $commentdata )
We can get author name, email, site url and comment content from $commentdata.
Here is the detail:
The $commentdata array contains the following indices: 'comment_post_ID' - The post to which the comment will apply 'comment_author' - (may be empty) 'comment_author_email' - (may be empty) 'comment_author_url' - (may be empty) 'comment_content' - The text of the proposed comment 'comment_type' - 'pingback', 'trackback', or empty for regular comments 'user_ID' - (empty if not logged in)
If we have got the spamming comment features, we can filter them.
As to preprocess_comment, it can allow us to process wordpress comment before inserting it to database.
Here is an example code for filtering wordpress spamming comments, you can add this code in your theme functions.php.
# process comments add_filter( 'preprocess_comment' , 'preprocess_spam_comment' ); function is_spam_comment($author_name, $author_url, $comment_content){ $author_names = explode($author_name, " "); if(count($author_names) > 3){ return true; } # contains url or other invalid symbol $arr=array("/","\\","!","@","#","$","%","^","&","*","(",")","+","=","[","]","{","}","'","\"",":",",",";"); foreach($arr as $a){ $pos = strpos($author_name,$a); if($pos === false){ }else{ return true; } } // check url $arr_2=array("?","=",'.xmc.pl'); foreach($arr_2 as $a){ $pos = strpos($author_url,$a); if($pos === false){ }else{ return true; } } // comment content $home_url = get_bloginfo('url'); $comment_content = str_replace($home_url,"",$comment_content); $arr_3=array("https:","http:"); foreach($arr_3 as $a){ $pos = strpos($comment_content,$a); if($pos === false){ }else{ return true; } } return false; } function preprocess_spam_comment( $commentdata ) { $author_url = $commentdata['comment_author_url']; $author_name = $commentdata['comment_author']; $comment_content = $commentdata['comment_content']; $flag = is_spam_comment($author_name, $author_url, $comment_content); if($flag){ die("spam comment"); } return $commentdata; }
Then, you will find many spmming comments will be filtered.