WordPress Spam Prevention Hack
Sunday, February 10th, 2008Posted in Web Apps • Tags: spam, wordpress
Akismet catches a lot of spam, but there is a lot it won’t catch. Therefore I decided to put together a hack to catch some more. The hack has 2 options:
- One for you to put in spam words that if they are in the comment, the whole comment will be considered spam. Just be careful, if you add cialis you will block the word specialist also.
- The other option lets you set the maximum number of links you will allow in a comment.
It will catch links that start with http://, https://, http://www., https://www. and www.. WordPress doesn’t convert text like example.com into a link.
The hack also checks to see if there is more content in the comment than just A tag(s), if there isn’t it’s considered spam. I recommend to use this with the Akismet plugin because it won’t prevent all spam. Keep in mind this hack may not work with other spam prevention plugins.
Open up wp-comments-post.php and after these lines
if ( '' == $comment_content )
wp_die( __('Error: please type a comment.') );
Add the following:
else /*MODIFIED - added this else to filter strings and count links*/
{
//OPTIONS
$link_limit = 3;//set the maximum number of links we allow
$disallowed_strings = array('[url', '[/url]', 'zithromax', 'levaquin');//add any strings you wont allow, make them lowercase, we test for case insensitivity later
//END OPTIONS
$temp_comment = strtolower($comment_content);//lowercase text so we can be case insensitive, php4 doesnt have stripos
$total_disallowed_strings = count($disallowed_strings);
//look for disallowed strings
for ($temp_counter = 0; $temp_counter < $total_disallowed_strings; $temp_counter++)
{
if (strpos($temp_comment, $disallowed_strings[$temp_counter]) !== false)
{
wp_die( __('Sorry, that looks like spam.') );
}
}
$comment_links = 0;
//regex would be better
$link_strings = array('http://www.', 'https://www.', 'http://', 'https://', 'www.');//order is important here
$temp_comment = str_replace($link_strings, '[LINK]', $temp_comment);
$comment_links = substr_count($temp_comment, '[LINK]');
//test for number of links
if ($comment_links > $link_limit)
{
wp_die( __('Sorry, that looks like spam.') );
}
//weed out all A tags and see if anything is left
$temp_comment = preg_replace('/<a[^\<]{1,}\<\/a\>/', '', $temp_comment);
$temp_comment = trim($temp_comment);
//see if the comment is nothing but links
if (empty($temp_comment))
{
wp_die( __('Sorry, that looks like spam.') );
}
}