Customise Comments

Using Googles NoCaptcha ReCaptcha In WordPress

Google has recently announced a new project called recaptcha which is a way of spam protecting your website from bots but making it easy for humans to submit the form by simply recreating a checkbox for users to click.

hero-recaptcha-demo

Registering Your Website

To use Google NoCaptcha ReCaptcha for your website you must first register your domain with the ReCaptcha API and get the site API key and the site secret API key.

Register Domain

When you have registered your website with the ReCaptcha API you can then collect the site key and the secret key, which you will need to use on your website to process the request.

Now we will learn how to use this in WordPress on the different default forms of:

  • Comment forms
  • Login forms
  • Lost password forms
  • New User forms

Load ReCaptcha Scripts

To get the ReCaptcha on your page you first need to load the Javascript on the page to do this we use the WordPress function wp_enqueue_script(), where we pass in the location of the Javascript for the ReCaptcha API.

https://www.google.com/recaptcha/api.js

Next we load our own custom JavaScript and CSS which we will need to use later in the tutorial to hide the default submit buttons and to have a callback function to display the submit buttons once a user has been verified as a human user. If you only want to use server side verification then you won't need to do this step of adding the CSS and JS.

add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('login_enqueue_scripts', array($this, 'enqueue_scripts'));

function enqueue_scripts()
{
    wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' );

    wp_enqueue_script( 'recaptcha-display-buttons', plugin_dir_url(__FILE__) . 'assets/js/public.js', array('jquery'));
    wp_enqueue_style( 'recaptcha-hide-buttons', plugin_dir_url(__FILE__) . 'assets/css/public.css');
}

Display ReCaptcha

The 4 forms that we are going to add the recaptcha on will each need the same code added to the bottom of the forms to display the recaptcha box, therefore we can create a single function which we can reuse on all the forms.

function display_recaptcha()
{
    echo '<div class="g-recaptcha" data-sitekey="{ENTER_SITE_KEY}" data-callback="recaptcha_callback"></div>';
}

Verify ReCaptcha

The next function we need to create are the server-side functions to verify the form handling with the Recaptcha API. The function we need to create is verify_captcha() which will be the function that we run on each of the form submit actions.

This will take a $_POST field created by the ReCaptcha which is submitted with the form and send this to the API with your site secret key. If the return of this is successful then we can submit the form data.

function verify_captcha( $parameter = true )
{
    if( isset( $_POST['g-recaptcha-response'] ) )
    {
        $response = json_decode(wp_remote_retrieve_body( wp_remote_get( "https://www.google.com/recaptcha/api/siteverify?secret={ENTER_SECRET_KEY}&response=" .$_POST['g-recaptcha-response'] ) ), true );

        if( $response["success"] )
        {
            return $parameter;
        }
    }

    return false;
}

Now we can use this on the 4 forms we are going to add it to on WordPress.

Login Page

As we made the display and verify of the ReCaptcha reusable we can use the same functions on each of the forms we just need to make sure that we add them at different times by using specific WordPress actions and filters.

To add the ReCaptcha to the login form we can use the action login_form and run the function display_recaptcha.

To verify the ReCaptcha input we use the filter wp_authenticate_user which is ran when the user tries to login, with the API fails we return false and the user can not login.

add_action( 'login_form', 'display_recaptcha' );
add_filter( 'wp_authenticate_user', 'verify_captcha' );

New User Registration

To add the ReCaptcha to the new user form you need to use the action register_form this will run at the bottom of the form and display the ReCaptcha box.

add_action( 'register_form', 'display_recaptcha' );
add_action( 'register_post', 'verify_captcha' );

Lost Password Form

To add the ReCaptcha to the lost password form you need to use the action lostpassword_form this will run at the bottom of the form and display the ReCaptcha box.

add_action( 'lostpassword_form', 'display_recaptcha' );
add_action( 'lostpassword_post', 'verify_captcha_lost_password' );

/**
 * Verify the lost password captcha
 */
 public function verify_captcha_lost_password( )
 {
     if( !verify_captcha() )
     {
         add_filter('allow_password_reset', '__return_false');
     }
 }

Comment Form

To add the ReCaptcha to the comment form you need to use the action comment_form this will run at the bottom of the form and display the ReCaptcha box.

add_action( 'comment_form', 'display_recaptcha' );
add_filter( 'preprocess_comment', 'verify_captcha' );

Hiding Submit Button On Forms

With the ReCaptcha script added to the different forms we need to make sure the user can not submit the form until they are verified which can be done by hiding the submit button on all the forms in the CSS.

#loginform #wp-submit,
#lostpasswordform #wp-submit,
#registerform #wp-submit,
#commentform #submit
{
    display: none;
}

Verified NoCaptcha ReCaptcha

Once the NoCaptcha AJAX API has come back and stated that this user is verified we can then display the submit button of the form, NoCaptcha will run the defined response function on the Captcha, in our example it's going to be recaptcha_callback().

Therefore we need to create a Javascript file to include our callback function, first we define the buttons that we want to search for, then we can loop through the buttons and check which ones are defined on the page, if the button is on the page then we can show it, allowing the user to submit the form.

function recaptcha_callback()
{
    var buttons = [
        '#loginform #wp-submit',
        '#lostpasswordform #wp-submit',
        '#registerform #wp-submit',
        '#commentform #submit'
    ];

    for(var i=0; i<=buttons.length; i++)
    {
        if($(buttons[i]).length > 0)
        {
            $(buttons[i]).show();
        }
    }
}

That's everything you need to get Google new NoCaptcha ReCaptcha on to the page.

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial