Are you fed up of moderating spam comments on your WordPress blog? It’s not rare to find spam comments that are written in a way that they appear as genuine feedback until you read it carefully or check the link. How not to spend time sifting through numerous spam comments, looking for one genuine response?
Though there is Akismet, a WordPress plug-in to stop spammers from flooding your blog, it requires a subscription if it’s not a personal blog. How about a code that will fight spammers by automatically deleting spam comments with certain words or phrases? Just copy and paste the following code in the functions.php
of your theme.
function in_comment_post_like($string, $array) {
foreach($array as $ref) { if(strstr($string, $ref)) { return true; } }
return false;
}
function drop_bad_comments() {
if (!empty($_POST[‘comment’])) {
$post_comment_content = $_POST[‘comment’];
$lower_case_comment = strtolower($_POST[‘comment’]);
// List of banned words in comments.
// Comments with these words will be auto-deleted.
$bad_comment_content = array(
‘viagra’,
‘hydrocodone’,
‘[url=http’,
‘[link=http’,
‘xanax’,
‘tramadol’,
‘lorazepam’,
‘adderall’,
‘dexadrine’,
‘no prescription’,
‘oxycontin’,
‘without a prescription’,
‘sex pics’,
‘family incest’,
‘online casinos’,
‘online dating’,
‘cialis’,
‘amoxicillin’
);
if (in_comment_post_like($lower_case_comment, $bad_comment_content)) {
wp_die( __(‘Darn! Your comment contains banned words.’) );
}
}
}
add_action(‘init’, ‘drop_bad_comments’);
In the $bad_comment_content
array, you can add the words that you find in your spams. Be sure to follow the order in which they have been listed—the word withing single quotes, followed by a comma. The last one in the array doesn’t have the comma.
Update: The code has been cleaned to remove an error.
Mr.AD says
Thanks for the code above ! That is the code I am finding !
Harsh Agrawal says
Thanks this is really helpful..Most of the time I manually remove spam..because Akismet flags legit comments as spam..!!!
Thanks for useful code..!!!
Rohan says
This thing is awesome… Good to make a self-sufficient blog.
max says
Thanx Pritam! Very useful code! No spam at all!
Indobisnis says
Thanks for sharing the code above ! this is really helpful…
arafin shaon says
works like a charm buddy tnx a lot 🙂
Jan says
Hi should i include all the line numbers 😉 would be more usefull if they where not included…
Sorry could just click view source thanks for a great information
Jefferson says
Very nice tip! This is going to prevent at least 2000 SPAMs/month in one of my blogs. Thanks!
Jefferson says
By the way, the code has a problem. The word “c*ialis” matches the word “spec*ialist” (remove the ‘*’)
Pritam says
Hey Jefferson, Thanks for pointing it out. Yes, it will delete those comments as well. If you are worried about it, you can delete that word from the list. 🙂