In this article, we will learn how to add google reCAPTCHA V2 in custom form.
First, we need to create a site key and secret key for google reCAPTCHA V2 and we can create using Google reCAPTCHA’s documentation.
There are two types of verification 1) Client-side and 2) server-side and we must add both verifications.
Google reCAPTCHA V2
Here is the step for adding google reCAPTCHA V2 on the site.
Client-side verification:
- Create HTML to display google reCAPTCHA in the form
<div class="g-recaptcha" data-sitekey="site_key" ></div>
To display reCAPTCHA, we must add the class name and data-sitekey attribute in this format only.
- Enqueue reCAPTCHA script and localize the script in the functions.php file
wp_enqueue_script( 'custom-captcha', 'https://www.google.com/recaptcha/api.js', 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', ) );
This is client-side verification and it’s not enough verification to protect from bots or spam.
Server-side verification:
- We can verify reCAPTCHA on the form submit.
- Call jquery function for getting token and save token in input type hidden
var token = grecaptcha.getResponse(); $( '.thc-g-recaptcha-response' ).val( token );
- Call ajax on form submit.
$( '.custom-form' ).on( 'submit', function( event ){ event.preventDefault(); var token = grecaptcha.getResponse(); $( '.thc-g-recaptcha-response' ).val( token ); $( '.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 ); } }); });
- Create an action function in the functions.php file and Call google reCAPTCHA API to verify reCAPTCHA
- 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> <div class="g-recaptcha" data-sitekey="site_key" ></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', 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', ) ); } add_action( 'wp_enqueue_scripts', 'child_theme_configurator_css', 10 );
Add jquery in the custom.js file
jQuery(document).ready(function($) { $( '.custom-form' ).on( 'submit', function( event ){ event.preventDefault(); var token = grecaptcha.getResponse(); $( '.thc-g-recaptcha-response' ).val( token ); $( '.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 ); } }); }); });
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 V2.
Here is a link for adding Google reCAPTCHA V3.