WordPress Spam Prevention Hack

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.') );
}
}

Tags: , ,

Comments 1-2 of 2 to “WordPress Spam Prevention Hack”

  1. 1 · Mark says:

    These 2 thing are built into WordPress. They’re under “Discussion Settings”

  2. 2 · blogger says:

    Part of it exists in WordPress, but all it does is put it in a queue to moderate it. This hack will prevent it from ever showing up, also it looks at the content and does a regex to see if any content was left or if only links were posted.

Leave a Comment

Comments are reviewed before publishing to prevent spam.