Integrating a CAPTCHA with the WordPress Comment Form

    Collins Agbonghama
    Share

    Over the years, WordPress has become a target for spammers due to it increasing popularity.

    Unfortunately, automated software exists whose purpose is to crawl the web in search of websites that are built with any popular platform, such as WordPress, and to submit hundreds, even thousands of spam comments. Spam comments are very annoying, they consume our precious time when it comes to moderating and deleting them.

    I know you hate spam comments as much as I do and would love to know how to combat them. One way of deterring bots from submitting spam comments is by integrating a CAPTCHA to the comment form.

    In previous tutorials, we learned how to integrate CAPTCHAs to the WordPress login and registration form.

    In similar fashion, we’ll now run through how to integrate a CAPTCHA with the WordPress comment system.

    There are many CAPTCHA plugins available in the WordPress plugin directory such as WP-reCAPTCHA and Securimage-WP-Fixed.

    The aim of this tutorial is to not create yet another CAPTCHA plugin but to:

    1. Demonstrate how the WordPress HTTP API can be used in a plugin.
    2. How to include additional form fields to the WordPress comment form.
    3. How to validate and utilise the values added to custom fields.

    Without further ado, let’s get started with the plugin development.

    Plugin Development

    First off, head over to reCAPTCHA, register your domain name and grab your public and private API keys.

    Include the plugin header.

    <?php
    
    /*
    Plugin Name: Add reCAPTCHA to comment form
    Plugin URI: https://www.sitepoint.com
    Description: Add Google's reCAPTCHA to WordPress comment form
    Version: 1.0
    Author: Agbonghama Collins
    Author URI: http://w3guy.com
    License: GPL2
    */

    Create a class with three properties that will store the reCAPTCHA’s private & public key as well as the CAPTCHA error message (errors are generated when the CAPTCHA form is left empty and a user fails the challenge).

    class Captcha_Comment_Form {
    
    	/** @type string private key|public key */
    	private $public_key, $private_key;
    
    	/** @type string captcha errors */
    	private static $captcha_error;

    The class magic constructor method will contain two pairs of action and filter hooks.

    /** class constructor */
    	public function __construct() {
    
    		$this->public_key  = '6Le6d-USAAAAAFuYXiezgJh6rDaQFPKFEi84yfMc';
    		$this->private_key = '6Le6d-USAAAAAKvV-30YdZbdl4DVmg_geKyUxF6b';
    
    		// adds the captcha to the WordPress form
    		add_action( 'comment_form', array( $this, 'captcha_display' ) );
                    
                    // delete comment that fail the captcha challenge
    		add_action( 'wp_head', array( $this, 'delete_failed_captcha_comment' ) );
    
    		// authenticate the captcha answer
    		add_filter( 'preprocess_comment', array( $this, 'validate_captcha_field' ) );
    
    		// redirect location for comment
    		add_filter( 'comment_post_redirect', array( $this, 'redirect_fail_captcha_comment' ), 10, 2 );
    	}

    Code explanation: First, my reCAPTCHA public and private keys are saved to their class properties.

    The captcha_display() method that will output the reCAPTCHA challenge is added to the comment form by the comment_form Action.

    The wp_head Action includes the callback function delete_failed_captcha_comment() that will delete any comment submitted that fail the CAPTCHA challenge.

    The filter preprocess_comment calls the validate_captcha_field() method to ensure the CAPTCHA field isn’t left empty and also that the answer is correct.

    The filter comment_post_redirect call redirect_fail_captcha_comment() to add some query parameters to the comment redirection URL.

    Here is the code for captcha_display() that will output the CAPTCHA challenge.

    Additionally, it check if there is a query string attached to the current page URL and display the appropriate error message depending on the value of $_GET['captcha'] set by redirect_fail_captcha_comment()

    /** Output the reCAPTCHA form field. */
    	public function captcha_display() {
    		if ( isset( $_GET['captcha'] ) && $_GET['captcha'] == 'empty' ) {
    			echo '<strong>ERROR</strong>: CAPTCHA should not be empty';
    		} elseif ( isset( $_GET['captcha'] ) && $_GET['captcha'] == 'failed' ) {
    			echo '<strong>ERROR</strong>: CAPTCHA response was incorrect';
    		}
    
    		echo <<<CAPTCHA_FORM
    		<style type='text/css'>#submit {
    				display: none;
    			}</style>
    		<script type="text/javascript"
    		        src="http://www.google.com/recaptcha/api/challenge?k=<?= $this->public_key; ?>">
    		</script>
    		<noscript>
    			<iframe src="http://www.google.com/recaptcha/api/noscript?k=<?= $this->public_key; ?>"
    			        height="300" width="300" frameborder="0"></iframe>
    			<br>
    			<textarea name="recaptcha_challenge_field" rows="3" cols="40">
    			</textarea>
    			<input type="hidden" name="recaptcha_response_field"
    			       value="manual_challenge">
    		</noscript>
    
    
    		<input name="submit" type="submit" id="submit-alt" tabindex="6" value="Post Comment"/>
    CAPTCHA_FORM;
    
    	}
    /**
    	 * Add query string to the comment redirect location
    	 *
    	 * @param $location string location to redirect to after comment
    	 * @param $comment object comment object
    	 *
    	 * @return string
    	 */
    	function redirect_fail_captcha_comment( $location, $comment ) {
    
    		if ( ! empty( self::$captcha_error ) ) {
    
    			$args = array( 'comment-id' => $comment->comment_ID );
    
    			if ( self::$captcha_error == 'captcha_empty' ) {
    				$args['captcha'] = 'empty';
    			} elseif ( self::$captcha_error == 'challenge_failed' ) {
    				$args['captcha'] = 'failed';
    			}
    
    			$location = add_query_arg( $args, $location );
    		}
    
    		return $location;
    	}

    The method validate_captcha_field() as its name implies to validate the CAPTCHA answer by making sure the CAPTCHA field isn’t left empty and the supplied answer is correct.

    /**
    	 * Verify the captcha answer
    	 *
    	 * @param $commentdata object comment object
    	 *
    	 * @return object
    	 */
    	public function validate_captcha_field( $commentdata ) {
    
    		// if captcha is left empty, set the self::$captcha_error property to indicate so.
    		if ( empty( $_POST['recaptcha_response_field'] ) ) {
    			self::$captcha_error = 'captcha_empty';
    		}
    
    		// if captcha verification fail, set self::$captcha_error to indicate so
    		elseif ( $this->recaptcha_response() == 'false' ) {
    			self::$captcha_error = 'challenge_failed';
    		}
    
    		return $commentdata;
    	}

    Let’s take a closer look at validate_captcha_field(), specifically the elseif conditional statement, a call is made to recaptcha_response() to check if the CAPTCHA answer is correct.

    Below is the code for the recaptcha_response().

    /**
    	 * Get the reCAPTCHA API response.
    	 *
    	 * @return string
    	 */
    	public function recaptcha_response() {
    
    		// reCAPTCHA challenge post data
    		$challenge = isset( $_POST['recaptcha_challenge_field'] ) ? esc_attr( $_POST['recaptcha_challenge_field'] ) : '';
    
    		// reCAPTCHA response post data
    		$response = isset( $_POST['recaptcha_response_field'] ) ? esc_attr( $_POST['recaptcha_response_field'] ) : '';
    
    		$remote_ip = $_SERVER["REMOTE_ADDR"];
    
    		$post_body = array(
    			'privatekey' => $this->private_key,
    			'remoteip'   => $remote_ip,
    			'challenge'  => $challenge,
    			'response'   => $response
    		);
    
    		return $this->recaptcha_post_request( $post_body );
    
    	}

    Allow me to explain how the recaptcha_response() works.

    A POST request is sent to the endpoint http://www.google.com/recaptcha/api/verify with the following parameters.

    • privatekey: Your private key
    • remoteip The IP address of the user who solved the CAPTCHA.
    • challenge The value of recaptcha_challenge_field sent via the form.
    • response The value of recaptcha_response_field sent via the form.

    The challenge and response POST data sent by the form is captured and saved to $challenge and $response respectively.
    $_SERVER["REMOTE_ADDR"] capture the user’s IP address and it to $remote_ip.

    WordPress HTTP API the POST parameter to be in array form hence the code below.

    $post_body = array(
    			'privatekey' => $this->private_key,
    			'remoteip'   => $remote_ip,
    			'challenge'  => $challenge,
    			'response'   => $response
    		);
    
    		return $this->recaptcha_post_request( $post_body );

    The recaptcha_post_request() is a wrapper function for the HTTP API which will accept the POST parameter/body, make a request to the reCAPTCHA API and return true if the CAPTCHA test was passed and false otherwise.

    /**
    	 * Send HTTP POST request and return the response.
    	 *
    	 * @param $post_body array HTTP POST body
    	 *
    	 * @return bool
    	 */
    	public function recaptcha_post_request( $post_body ) {
    
    		$args = array( 'body' => $post_body );
    
    		// make a POST request to the Google reCaptcha Server
    		$request = wp_remote_post( 'https://www.google.com/recaptcha/api/verify', $args );
    
    		// get the request response body
    		$response_body = wp_remote_retrieve_body( $request );
    
    		/**
    		 * explode the response body and use the request_status
    		 * @see https://developers.google.com/recaptcha/docs/verify
    		 */
    		$answers = explode( "\n", $response_body );
    
    		$request_status = trim( $answers[0] );
    
    		return $request_status;
    	}

    Any comment made by a user who failed the captcha challenge or left the field empty get deleted by delete_failed_captcha_comment()

    /** Delete comment that fail the captcha test. */
    	function delete_failed_captcha_comment() {
    		if ( isset( $_GET['comment-id'] ) && ! empty( $_GET['comment-id'] ) ) {
    
    			wp_delete_comment( absint( $_GET['comment-id'] ) );
    		}
    	}

    Finally, we close the plugin class.

    } // Captcha_Comment_Form

    We are done coding the plugin class. To put the class to work, we need to instantiate it like so:

    new Captcha_Comment_Form();

    On activation of the plugin, a CAPTCHA will be added to the WordPress comment form as show below.

    CAPTCHA on a WordPress Comment Form

    Wrap Up

    At the end of this tutorial, you should be able to add extra form fields to the comment form and implement just about any feature you wish to have in the comment system thanks to the filters and actions mentioned.

    If you wish to use the plugin on your WordPress site or to study the code in-depth, download the plugin from GitHub.

    Until I come your way again, happy coding!