Fighting WordPress Comment Spam with a Nonce

Fighting WordPress Comment Spam with a Nonce

In addition to blocking the comment spam bots that don’t include a HTTP_REFERER header indicating the request came from your web site, as indicated in a previous posting Fight Back Against WordPress Comment Spam with a HTTP_REFERER Check, additional steps can be taken to combat comment spam. This post will discuss the addition of a nonce field to your comment form that verifies the request came from your web site and not from somewhere else.

What is a nonce?

Nonce was a term that was developed to mean “for or used on one occasion.” In short, a nonce is a generated value. A nonce value is generated on every page request, and validated on the next subsequent action or additional page request to ensure any request or action to be performed came from your web site.

WordPress leverages the nonce field throughout its administrative tooling to verify the actions being taken are being performed within an appropriate session and by an appropriate user. We can leverage this same functionality within other aspects of our WordPress web site, like the comment form, to ensure that the request truly did originate within the proper channels effectively eliminating comment spam bots.

This will require any comment spam bots to have a valid nonce value before allowing their comment to be submitted for processing. Seeing as this field is generated and unique for each and every request, it is highly unlikely that a comment spam bot will be able to replicate it, effectively removing spam comments form your web site.

NOTE: A nonce does not offer absolute protection, but will and should provide protection against invalid requests in most cases.

To enable the nonce field within your WordPress comment form add the following code snippet to your functions.php file, within your WordPress theme folder, to enable the nonce field support for your comment form.

// Generate Nonce
function add_nonce_field_to_comment_form() {
    wp_nonce_field('comment_form_nonce_field');
}

// Add Nonce To Comment Form 
add_action('comment_form', 'add_nonce_field_to_comment_form');

// Check Nonce Field Validity
function check_nonce_field_on_comment_form() {
    if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'comment_form_nonce_field')) {
        die('Nonce Check Failed - Killing Request');
    }
}

// Add Nonce Check To Comment Form Post
add_action('pre_comment_on_post', 'check_nonce_field_on_comment_form');

Author: daharveyjr

I’m a solution architect responsible for the design, development, implementation, testing, and maintenance of e-commerce operations and applications using the Hybris and WebSphere Commerce product suites and other web technologies such as Java, J2EE/JEE, Spring, PHP, WordPress and more. Twitter | Facebook | LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *