Integrating a CAPTCHA with the WordPress Registration Form

By Collins Agbonghama
We teamed up with SiteGround
To bring you the latest from the web and tried-and-true hosting, recommended for designers and developers. SitePoint Readers Get Up To 65% OFF Now

In previous tutorials, we took a deep dive into WordPress HTTP API, learned how to use the HTTP API in consuming APIs in plugins during the course of building a widget that displays WHOIS and social data of a domain and integrating a CAPTCHA with the WordPress login form.

In this tutorial, we will code a plugin that will this time around, integrate CAPTCHA (Google’s reCAPTCHA) to the default WordPress registration form. Of course, the HTTP API will be used to communicate with reCAPTCHA endpoint to verify the answer supplied by a user to the CAPTCHA challenge.

Below is a screenshot of the registration form protected by CAPTCHA to prevent spam registration.

CAPTCHA with the WordPress Registration Form

Why Include a CAPTCHA with the Registration Form?

Due to the increasing popularity of WordPress, it has become an easy target for unscrupulous automated software. This software crawls the web in search of websites built with WordPress and starts registering hundreds and thousands of accounts every minute.

In my early WordPress days, I can still remember waking up one morning with my mailbox filled with notifications for over fifty registered user accounts.

One of the proven and trusted ways of reducing and perhaps eliminating spam completely is by implementing CAPTCHAs to web forms.

A CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass and that current software programs cannot.

By integrating CAPTCHA to a WordPress registration form, spam registration will soon become a thing of the past.

Plugin Development

Before we begin coding the plugin, let’s head over to reCAPTCHA, register your domain name and grab your public and private API keys.

First off, include the plugin header.


Plugin Name: reCAPTCHA in WP Registration Form
Plugin URI:
Description: Add Google's reCAPTCHA to WordPress registration form
Version: 1.0
Author: Agbonghama Collins
Author URI:
License: GPL2

Create a PHP class with two properties that will store your reCAPTCHA’s private and public key.

class Captcha_Registration_Form {

	/** @type string private key|public key */
	private $public_key, $private_key;

The plugin constructor method will consist of two action hooks that will add the CAPTCHA challenge to the registration form and verify the CAPTCHA response.

/** class constructor */
	public function __construct() {
		$this->public_key  = '6Le6d-USAAAAAFuYXiezgJh6rDaQFPKFEi84yfMc';
		$this->private_key = '6Le6d-USAAAAAKvV-30YdZbdl4DVmg_geKyUxF6b';

		// adds the captcha to the registration form
		add_action( 'register_form', array( $this, 'captcha_display' ) );

		// authenticate the captcha answer
		add_action( 'registration_errors', array( $this, 'validate_captcha_field' ), 10, 3 );

The captcha_display() method that will output the reCAPTCHA challenge is added to the WordPress registration form by the register_form action.

The validate_captcha_field() method that will ensure: the CAPTCHA field isn’t left empty and also verify the answer supplied by the user; is added to the registration validation system by the registration_errors action.

Below is the code for the captcha_display() and validate_captcha_field() method we talked about.

/** Output the reCAPTCHA form field. */
	public function captcha_display() {
		<script type="text/javascript"
			<iframe src="<?=$this->public_key;?>"
			        height="300" width="300" frameborder="0"></iframe>
			<textarea name="recaptcha_challenge_field" rows="3" cols="40">
			<input type="hidden" name="recaptcha_response_field"

	 * Verify the captcha answer
	 * @param $user string login username
	 * @param $password string login password
	 * @return WP_Error|WP_user
	public function validate_captcha_field($errors, $sanitized_user_login, $user_email) {

		if ( ! isset( $_POST['recaptcha_response_field'] ) || empty( $_POST['recaptcha_response_field'] ) ) {
			$errors->add( 'empty_captcha', '<strong>ERROR</strong>: CAPTCHA should not be empty');

		if( $this->recaptcha_response() == 'false' ) {
			$errors->add( 'invalid_captcha', '<strong>ERROR</strong>: CAPTCHA response was incorrect');

		return $errors;

Taking a closer look at the validate_captcha_field() specifically the second if conditional statement, a call is made to recaptcha_response() to check if the CAPTCHA answer is correct (false is returned if the CAPTCHA response is wrong).

Let’s see the code and explanation of 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 );


Code explanation: To verify that the CAPTCHA answer supplied by the user is correct, a POST request is sent to the endpoint 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.

First, the challenge and response POST data sent by the form is captured and saved to $challenge and $response respectively.

The IP address of the user is captured by $_SERVER["REMOTE_ADDR"] and saved to $remote_ip.

To send a POST request with the HTTP API, the parameters or body must be in an array form as shown below:

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

The POST parameters are passed as an argument to the recaptcha_post_request() which then sends the request along with the parameters to and return the API response.

recaptcha_post_request() returns true if the CAPTCHA answer is correct and false otherwise.

Below is the code for recaptcha_post_request()

	 * 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( '', $args );

		// get the request response body
		$response_body = wp_remote_retrieve_body( $request );

		 * explode the response body and use the request_status
		 * @see
		$answers = explode( "\n", $response_body );

		$request_status = trim( $answers[0] );

		return $request_status;

Code explanation: An array $args with the POST body $post_body saved to the key body is created.

The wp_remote_post sends the POST request with the response saved to $request.

The response body is retrieved by the wp_remote_retrieve_body and saved to $response_body.

If the CAPTCHA test was passed, the reCAPTCHA API returns:


Otherwise the following error is returned


To get the recaptcha_post_request method to return a Boolean value i.e. true on success and false on failure; the response $response_body is exploded and the array data with index 0 trimmed to remove any redundant white space from the beginning and end of the string.

Finally, we close the plugin class.

} // Captcha_Registration_Form

To put the class to action, we need to instantiate it like so:

new reCAPTCHA_Login_Form();

Wrap Up

If you wish to use the plugin on your WordPress site or to study the code, download the plugin from my GitHub repository.

This is the third in a series that demonstrates how the WordPress HTTP API can be used in a plugin to consume APIs.

Be sure to keep an eye on the WordPress channel for similar tutorials.

Happy coding!

We teamed up with SiteGround
To bring you the latest from the web and tried-and-true hosting, recommended for designers and developers. SitePoint Readers Get Up To 65% OFF Now
  • “One of the proven and trusted ways of reducing and perhaps eliminating spam completely is by implementing CAPTCHAs to web forms.” I’d love to see a skerrick of evidence for this.

    • Although most people consider CAPTCHAS bad UX however, they still help in great deal in fighting spam.

      Millions of website trust Google reCAPTCHA in protecting we forms against spam.

      • That’s not evidence. But then, there isn’t any evidence to show they work. They’re not trusted – they’re implemented because articles like this propagate the myth that they work, despite the fact they don’t work at all well. You’re relying on spin and nonsense to talk up a methodology that is fundamentally flawed, and you’re ignoring the very serious accessibility issues CAPTCHAs present. And you should read up on how flawed reCAPTCHA is, in particular. It’s disappointing SitePoint propagates this rubbish, especially when it makes the web just that bit less accessible, is unnecessary and does not work.

        • You are right, no contradiction.

          Like with every article published here on sitepoint, the aim is to teach users how things work.

          For example: it’s clear you have no love for CAPTCHAs and maybe you have better alternative to combat spam.
          Looking beyond the title of this piece, the tutorial will come in handy in teaching you how an alternative can be implemented in WordPress.

          In a nutshell, Tutorials of this type shows people how stuff is or can be done.


          • Uh, yes, Agbonghama. I think I “grab” how tutorials on SitePoint are supposed to work. I also know that SitePoint has a responsibility to teach not just “how things work”, but how to do things right. This is the essence of the web conference SitePoiint was just a sponsor at, and it is the opposite of what this articles does. There is no point in showing people how bad practice can be maintained.

        • Craig Buckler, SitePoint, 14 May 2009: “All CAPTCHA systems are doomed to fail.
          Unfortunately, this has not prevented eager developers using CAPTCHAs in
          even the most basic web to email forms.

          No one likes CAPTCHAs. They are not fun. They can not be used by
          everyone, such as those with impaired vision or without graphics enabled”.

          Agbonghama, we don’t have a reliable way of combatting form and comment spam that a dev can implement. All mechanised ways of combatting spam have flaws, and CAPTCHA has more flaws than any of them.

  • rogledi

    Seriously? again captchas?