Allan Vest

Expert Web Development

How To Stop Comment Spam

leave a comment

Comment spam is a nuisance. Here’s a simple piece of code you can add to your WordPress blog (or any web form) that stops nearly all of the spam without asking your site visitors to do anything extra.

I’ve been adding this bit of code to my forms and to the forms of my clients for years. So far, it has worked extremely well. I almost hate to give the secret away in fear that the bad guys will start checking for it.

Most comment spam is completely automated. Which is why we can easily prevent it. Somewhere someone not so nice wrote a simple program that crawls web pages looking for any page that has a form on it. Once a form page is found, the program does a “POST” directly to the form processing page.

Now the goal of these comment spam scripts is to quickly find as many forms as possible without any human assistance.  The code below counts on the fact that the bad guys are simply too lazy to go to each site and submit comments by hand and their programs are not sophisticated enough to actually simulate processing the javascript embedded on a web page when doing a form submission.

Here’s the solution in WordPress:

For the following code, replace the references to “YOUR_FORM_VARIABLE_NAME” with a unique name of your own and replace “YOUR_FORM_VARIABLE_VALUE” with a unique value of your own.

Make a copy of the wp-comments-post.php file.

Find the following line of code:

$status_obj = get_post_status_object($status);

And insert the following code just below:

$is_spam = false;
$validate = trim($_POST['YOUR_FORM_VARIABLE_NAME']);
if ($validate <> 'YOUR_FORM_VARIABLE_VALUE')
     $is_spam = true;
if ($is_spam)
     do_action('comment_closed', $comment_post_ID);
     wp_die( __('Sorry, comments are closed for this item.') );

Now go to the wp-content/themes/ folder, find your theme folder, and then make a copy of the comments.php file.

Open the comments.php file and find the form tag:

<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php"
method="post" id="commentform">

Replace the form tag with:

function is_ready(a_form)
     a_form.validate.value = "YOUR_FORM_VARIABLE_VALUE";
     return true;
<form onSubmit="return is_ready(this);"
action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php"
method="post" id="commentform">
<input type="hidden" name="YOUR_FORM_VARIABLE_NAME"
id="YOUR_FORM_VARIABLE_NAME" value="" />

That’s it!

Written by allan

March 28th, 2011 at 3:25 pm

Posted in Web Development

Leave a Reply