Add Recaptcha in Custom Form in WordPress

Add Recaptcha in Custom Form in Wordpress
1666 Views
3.8
(63)

You have to add recaptcha external js so use following function in your current themes functions.php file

<?php
add_action( 'wp_enqueue_scripts', 'cxc_enqueue_my_styles_scripts' );  

function cxc_enqueue_my_styles_scripts() {
	wp_enqueue_script( 'recaptcha-script', 'https://www.google.com/recaptcha/api.js' );
	wp_enqueue_script( 'custom_script', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true );
}
?>

Set Recaptcha element in your form.

Cxc Custom Form :

Custom Form Html :

<form class="cxc-captcha-form">
   <input name="name" type="text" placeholder="Enter Your Name">
   <input name="email" type="email" placeholder="Enter Your Email">
   <div class="g-recaptcha" data-sitekey="{{** Enter Your Sitekey Here **}}"></div>
   <div class="captcha-error" style="color: red;"></div>
   <input name="submit" type="submit" value="Submit">
</form>

Put below js in your current themes custom.js file.

//Captcha validation script
jQuery(document).ready(function( $ ) { 
	jQuery(document).on('submit','.cxc-captcha-form',function(e){
		if(grecaptcha.getResponse() == "") {
		   	e.preventDefault();
			jQuery('.captcha-error').text("Please verify captcha");
		} else {
			jQuery('.captcha-error').text("");
		}
	});
});

How useful was this blog?

Click on a star to rate it!

Average rating 3.8 / 5. Vote count: 63

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *