How To Add Google reCAPTCHA V3 In The Custom Form In The WordPress

In this article, we will learn how to add google reCAPTCHA V3 in custom form.

First, we need to create a site key and secret key for google reCAPTCHA V3 and we can start using google reCAPTCHA’s documentation.

To protects the website from spam and abuse we use google reCAPTCHA.

There are two types of verification 1) Client-side and 2) server-side and we must add both verifications.

Google reCAPTCHA V3

Here is the step for adding google reCAPTCHA V3 on the site.

Client-side verification:

  1. Create HTML to save tokens in the form
    <input type="hidden" name="g-recaptcha-response" id="thc-g-recaptcha-response" class="thc-g-recaptcha-response">
  2. Enqueue reCAPTCHA script and localize the script in the functions.php file
    wp_enqueue_script( 'custom-captcha', 'https://www.google.com/recaptcha/api.js?render=site_key', array(), '', true );
    wp_enqueue_script( 'custom', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true );
    wp_localize_script( 'custom', 'data',
                array( 
                    'ajaxurl' => admin_url( 'admin-ajax.php' ),
                    'recaptcha_site_key' => 'site_key',
                    'recaptcha_secret_key' => 'secret_key',
                )
    );
  3. Create jquery function for getting token and save token in input type hidden to further use.
    function getRecaptcha() {
        grecaptcha.ready(function () {
            grecaptcha.execute( data.recaptcha_site_key, { action: 'submit' }).then( function( token ) {
                jQuery( '.thc-g-recaptcha-response' ).val( token );
            });
        });
    }
  4. Call this function on page load to generate a token
    if ( $( '.custom-form' ).find( '.thc-g-recaptcha-response' ).length ) {
            getRecaptcha();
        }
  5. Once the token generates google reCAPTCHA verify.

This is client-side verification and it’s not enough verification to protect from bots or spam.

Server-side verification:

  1. We can verify reCAPTCHA differently like on form submit, on click verify button. Here we verify reCAPTCHA on form submit.
  2. Call ajax on form submit.
    $( '.custom-form' ).on( 'submit', function( event ){
            event.preventDefault();
            $( '.thc-action' ).val( 'custom_form_action' );
            $( '.recaptcha-secret-key' ).val( data.recaptcha_secret_key );
            var formData = new FormData( this );
    
            jQuery.ajax({
                url: data.ajaxurl,
                type: 'post',
                processData: false,
                contentType: false,
                data: formData,
                beforeSend: function() {
                    
                },
                success: function( data ) {
                    var data = $.parseJSON( data );
                    $( '.thc-message' ).html( data.message );
                }
            });
        });
  3. Create an action function in the functions.php file and Call google reCAPTCHA API to verify reCAPTCHA
  4. Here we can get different error and success messages from the reCAPTCHA API.
    add_action( 'wp_ajax_custom_form_action', 'custom_form_action' );
    add_action( 'wp_ajax_nopriv_custom_form_action', 'custom_form_action' );
    
    function custom_form_action() {
        if( isset( $_POST['g-recaptcha-response'] ) && $_POST['g-recaptcha-response'] != '' ) {
            $captcha_token = $_POST['g-recaptcha-response'];
            $secret_key = $_POST['recaptcha_secret_key'];
            // post request to server
            $captcha_url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode( $secret_key ) .  '&response=' . urlencode( $captcha_token );
            $captcha_response = wp_remote_get( $captcha_url, array() );
            $responseKeys = json_decode( wp_remote_retrieve_body( $captcha_response ), true );
    
            if( $responseKeys["success"] ) {
                $output = array(
                    'message' => __( "Valid recaptcha", "thecodehubs" )
                );
            } else {
                $error_codes = array(
                  'missing-input-secret' 	=> 'The secret key is missing Please add a secret key',
                  'invalid-input-secret' 	=> 'You have added the wrong secret Key. Please add a correct secret key',
                  'missing-input-response' 	=> 'Captcha token is missing please check you site key',
                  'invalid-input-response' 	=> 'Captcha token is invalid please check site key and secret key',
                  'timeout-or-duplicate' 	=> 'captcha token expire please refresh the page and submit the form again',
                );
                $captchaerrormsg = '';
                $captchaerrors = $responseKeys['error-codes'];
                foreach( $captchaerrors as $captchaerror ) {
                    if( array_key_exists( $captchaerror, $error_codes ) ) {
                        $captchaerrormsg .= $error_codes[$captchaerror]. "<br>";
                    } else {
                        $captchaerrormsg .= 'The form submission was blocked by reCAPTCHA<br>';
                    }
                }
                $output = array(
                    'message' => __( $captchaerrormsg, 'thecodehubs' )
                );
            }
        } else {
            $output = array(
                'message' => __( "You have added the wrong site Key. Please add a correct site key", "thecodehubs" )
            );
        }
        echo json_encode( $output );
        die;
    }

Here is a combined code for easily understand

HTML

You can add form HTML in page templates or page editors.

<form action="" method="post" class="custom-form">
  <div class="custom-placeholder-wrap">
    <label class="placeholder">Your name<span class="required">*</span></label>
    <input type="text" name="your-name" value="" size="40" class="" aria-required="true" aria-invalid="false">
  </div>
  <div class="custom-placeholder-wrap">
    <label class="placeholder" style="">Your email<span class="required">*</span></label>
    <input type="email" name="your-email" value="" size="40" class="" aria-required="true" aria-invalid="false">
  </div>
  <div class="custom-placeholder-wrap">
    <label class="placeholder">Your message</label>
    <textarea name="your-message" cols="40" rows="10" class="form-textarea" aria-invalid="false" spellcheck="false"></textarea>
  </div>
        
  <input type="hidden" name="g-recaptcha-response" id="thc-g-recaptcha-response" class="thc-g-recaptcha-response">
        <input type="hidden" name="action" class="thc-action" value="">
        <input type="hidden" name="recaptcha_secret_key" class="recaptcha-secret-key" value="">
        <p class="thc-message"></p>
  <input type="submit" value="Submit" class="form-submit">
  
</form>

Enqueue script functions.php file

    function child_theme_configurator_css() {
        wp_enqueue_script( 'custom-captcha', 'https://www.google.com/recaptcha/api.js?render=site_key', array(), '', true );
        wp_enqueue_script( 'custom', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true );
        wp_localize_script( 'custom', 'data',
            array( 
                'ajaxurl' => admin_url( 'admin-ajax.php' ),
                'recaptcha_site_key' => 'site_key',
                'recaptcha_secret_key' => 'secrete_key',
            )
        );
    }
add_action( 'wp_enqueue_scripts', 'child_theme_configurator_css', 10 );


Add jquery in the custom.js file

jQuery(document).ready(function($) {
    if ( $( '.custom-form' ).find( '.thc-g-recaptcha-response' ).length ) {
        getRecaptcha();
    }

    $( '.custom-form' ).on( 'submit', function( event ){
        event.preventDefault();
        $( '.thc-action' ).val( 'custom_form_action' );
        $( '.recaptcha-secret-key' ).val( data.recaptcha_secret_key );
        var formData = new FormData( this );

        jQuery.ajax({
            url: data.ajaxurl,
            type: 'post',
            processData: false,
            contentType: false,
            data: formData,
            beforeSend: function() {
                
            },
            success: function( data ) {
                var data = $.parseJSON( data );
                $( '.thc-message' ).html( data.message );
            }
        });
    });
});

function getRecaptcha() {
    grecaptcha.ready(function () {
        grecaptcha.execute( data.recaptcha_site_key, { action: 'submit' }).then( function( token ) {
            jQuery( '.thc-g-recaptcha-response' ).val( token );
        });
    });
}

Add action function in functions.php file

add_action( 'wp_ajax_custom_form_action', 'custom_form_action' );
add_action( 'wp_ajax_nopriv_custom_form_action', 'custom_form_action' );

function custom_form_action() {
    if( isset( $_POST['g-recaptcha-response'] ) && $_POST['g-recaptcha-response'] != '' ) {
        $captcha_token = $_POST['g-recaptcha-response'];
        $secret_key = $_POST['recaptcha_secret_key'];
        // post request to server
        $captcha_url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode( $secret_key ) .  '&response=' . urlencode( $captcha_token );
        $captcha_response = wp_remote_get( $captcha_url, array() );
        $responseKeys = json_decode( wp_remote_retrieve_body( $captcha_response ), true );

        if( $responseKeys["success"] ) {
            $output = array(
                'message' => __( "Valid recaptcha", "thecodehubs" )
            );
        } else {
            $error_codes = array(
              'missing-input-secret' 	=> 'The secret key is missing Please add a secret key',
              'invalid-input-secret' 	=> 'You have added the wrong secret Key. Please add a correct secret key',
              'missing-input-response' 	=> 'Captcha token is missing please check you site key',
              'invalid-input-response' 	=> 'Captcha token is invalid please check site key and secret key',
              'timeout-or-duplicate' 	=> 'captcha token expire please refresh the page and submit the form again',
            );
            $captchaerrormsg = '';
            $captchaerrors = $responseKeys['error-codes'];
            foreach( $captchaerrors as $captchaerror ) {
                if( array_key_exists( $captchaerror, $error_codes ) ) {
                    $captchaerrormsg .= $error_codes[$captchaerror]. "<br>";
                } else {
                    $captchaerrormsg .= 'The form submission was blocked by reCAPTCHA<br>';
                }
            }
            $output = array(
                'message' => __( $captchaerrormsg, 'thecodehubs' )
            );
        }
    } else {
        $output = array(
            'message' => __( "You have added the wrong site Key. Please add a correct site key", "thecodehubs" )
        );
    }
    echo json_encode( $output );
    die;
}

Here is an Output:

 

This code is applicable for reCAPTCHA version V3.

Here is a link for adding Google reCAPTCHA V2.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories