Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

Integrating Google No Captcha reCaptcha In WordPress Forms

In this tutorial you will learn how to integrate Google’s new reCatcha model in WordPress Login, Comment, Registration and Lost Password Forms.

Google No Captcha reCaptcha

There are many different solutions to prevent bots from submitting web forms. But one of the most popular solution was using reCaptcha. reCaptcha actually displays a image with some text in it and user has to enter the text to submit the form successfully. It was difficult for bots to read the text on the image. But as bots algorithms become more advanced they started breaking this security. It was no more safe. This old method has a pretty bad in terms of user friendliness. There Google came with a new reCaptcha called No Captcha reCaptcha.

In this tutorial we will look at what exactly No Captcha reCaptcha is and how to create a plugin which integrates reCaptcha in the WordPress Login, Registration and Comment forms.

A Look at No Captcha reCaptcha

Google No Captcha reCaptcha

No Captcha reCaptcha just displays a check box asking the user to check it if he/she is not a bot. It might look very hackable but internally Google uses advanced algorithms and methods to find if the user is a bot or not. This new model is more user friendly and secure than the old one.

Registering Your Site and Retrieving Keys

Users who install this plugins needs to register their website to retrieve site key and secret key.

You need to create a settings page for the plugin which allows the WordPress administrator to install the site key and secret key they retrieved from reCaptcha admin panel.

function no_captcha_recaptcha_menu() {
	add_menu_page("reCapatcha Options", "reCaptcha Options", "manage_options", "recaptcha-options", "recaptcha_options_page", "", 100);
}

function recaptcha_options_page() { ?>
	<div class="wrap">
		<h1>reCaptcha Options</h1>
		<form method="post" action="options.php">
		<?php settings_fields("header_section");
			do_settings_sections("recaptcha-options");
			submit_button(); ?>          
		</form>
	</div>
<?php }
add_action("admin_menu", "no_captcha_recaptcha_menu");

function display_recaptcha_options() {
	add_settings_section("header_section", "Keys", "display_recaptcha_content", "recaptcha-options");

	add_settings_field("captcha_site_key", __("Site Key"), "display_captcha_site_key_element", "recaptcha-options", "header_section");
	add_settings_field("captcha_secret_key", __("Secret Key"), "display_captcha_secret_key_element", "recaptcha-options", "header_section");

	register_setting("header_section", "captcha_site_key");
	register_setting("header_section", "captcha_secret_key");
}

function display_recaptcha_content() {
	echo __('<p>You need to <a href="https://www.google.com/recaptcha/admin" rel="external">register you domain</a> and get keys to make this plugin work.</p>');
	echo __("Enter the key details below");
}

function display_captcha_site_key_element() { ?>
	<input type="text" name="captcha_site_key" id="captcha_site_key" value="<?php echo get_option('captcha_site_key'); ?>" />
<?php }

function display_captcha_secret_key_element() { ?>
	<input type="text" name="captcha_secret_key" id="captcha_secret_key" value="<?php echo get_option('captcha_secret_key'); ?>" />
<?php }
add_action("admin_init", "display_recaptcha_options");

Let’s see how the above code works:

  • We created a settings page on WordPress admin dashboard.
  • This settings page displays two input text fields. These input fields accept site key and secret key.
  • These keys are stored as WordPress options. We name the options as site_key and secret_key.

Add No Captcha reCaptcha to WP Comment Forms

You need to integrate reCaptcha in frontend comments forms to prevent bots from putting spam comments.

Create a style.css file in your plugin directory and place this code

#submit {
	display: none;
	}

The above code hides the submit button in WordPress comment form. So that we can place the reCaptcha box above the submit button by inserting both submit button and reCaptcha box manually.

Here is the code to integrate reCaptcha on comment forms:

function frontend_recaptcha_script() {
	wp_register_script("recaptcha", "https://www.google.com/recaptcha/api.js");
	wp_enqueue_script("recaptcha");
	
	$plugin_url = plugin_dir_url(__FILE__);
	wp_enqueue_style("no-captcha-recaptcha", $plugin_url ."style.css");
}
add_action("wp_enqueue_scripts", "frontend_recaptcha_script");

function display_comment_recaptcha() { ?>
	<div class="g-recaptcha" data-sitekey="<?php echo get_option('captcha_site_key'); ?>"></div>
	<input name="submit" type="submit" value="Submit Comment">
<?php }
add_action("comment_form", "display_comment_recaptcha");

function verify_comment_captcha($commentdata) {
	if (isset($_POST['g-recaptcha-response'])) {
		$recaptcha_secret = get_option('captcha_secret_key');
		$response = wp_remote_get("https://www.google.com/recaptcha/api/siteverify?secret=". $recaptcha_secret ."&response=". $_POST['g-recaptcha-response']);
		$response = json_decode($response["body"], true);
		if (true == $response["success"]) {
			return $commentdata;
		} else {
			echo __("Bots are not allowed to submit comments.");
			return null;
		}
	} else {
		echo __("Bots are not allowed to submit comments. If you are not a bot then please enable JavaScript in browser.");
		return null;
	}
}
add_filter("preprocess_comment", "verify_comment_captcha");

Let’s see how the above code works:

  • We en-queued the Google’s reCaptcha JavaScript file to WordPress frontend by using wp_enqueue_scripts action.
  • We also en-queued the style.css file using wp_enqueue_style
  • Inside the comment form we display the checkbox using comment_form action.
  • When comment is submitted and before inserting it to the database WordPress calls the preprocess_comment filter. Inside the filter we check if the user is human or bot. If human then we return the comment to be inserted otherwise we return null to prevent the comment from being added to database.

Add No Captcha reCaptcha to the WP Login Form

We need to integrate reCaptcha in admin login form to prevent bots from running a brute force attack to crack passwords. Here is the code to integrate it on admin login form:

function login_recaptcha_script() {
	wp_register_script("recaptcha_login", "https://www.google.com/recaptcha/api.js");
	wp_enqueue_script("recaptcha_login");
}
add_action("login_enqueue_scripts", "login_recaptcha_script");

function display_login_captcha() { ?>
	<div class="g-recaptcha" data-sitekey="<?php echo get_option('captcha_site_key'); ?>"></div>
<?php }
add_action( "login_form", "display_login_captcha" );

function verify_login_captcha($user, $password) {
	if (isset($_POST['g-recaptcha-response'])) {
		$recaptcha_secret = get_option('captcha_secret_key');
		$response = wp_remote_get("https://www.google.com/recaptcha/api/siteverify?secret=". $recaptcha_secret ."&response=". $_POST['g-recaptcha-response']);
		$response = json_decode($response["body"], true);
		if (true == $response["success"]) {
			return $user;
		} else {
			return new WP_Error("Captcha Invalid", __("<strong>ERROR</strong>: You are a bot"));
		} 
	} else {
		return new WP_Error("Captcha Invalid", __("<strong>ERROR</strong>: You are a bot. If not then enable JavaScript"));
	}   
}
add_filter("wp_authenticate_user", "verify_login_captcha", 10, 2);

Let’s see how the above code works:

  • We en-queued the Google’s reCaptcha JavaScript file to WordPress admin login, registration and lost password pages by using login_enqueue_scripts action.
  • We displayed the checkbox using login_form action.
  • Before producing the final authentication result WordPress runs the wp_authenticate_user filter to let us add a extra validation step. We check if the user is bot or human inside this filter. If its human we return the user object else we return and WordPress error object.

Add No Captcha reCaptcha to the WP Registration Form

We need to integrate reCaptcha in admin registration form to prevent bots from creating fake accounts. Here is the code to integrate it on admin registration form:

function display_register_captcha() { ?>
	<div class="g-recaptcha" data-sitekey="<?php echo get_option('captcha_site_key'); ?>"></div>
<?php }
add_action("register_form", "display_register_captcha");

function verify_registration_captcha($errors, $sanitized_user_login, $user_email) {
	if (isset($_POST['g-recaptcha-response'])) {
		$recaptcha_secret = get_option('captcha_secret_key');
		$response = wp_remote_get("https://www.google.com/recaptcha/api/siteverify?secret=". $recaptcha_secret ."&response=". $_POST['g-recaptcha-response']);
		$response = json_decode($response["body"], true);
		if (true == $response["success"]) {
			return $errors;
		} else {
			$errors->add("Captcha Invalid", __("<strong>ERROR</strong>: You are a bot"));
		}
	} else {
		$errors->add("Captcha Invalid", __("<strong>ERROR</strong>: You are a bot. If not then enable JavaScript"));
	}
	return $errors;
}
add_filter("registration_errors", "verify_registration_captcha", 10, 3);

Let’s see how the above code works:

  • We displayed the checkbox using register_form action.
  • Before producing the final authentication result WordPress runs the registration_errors filter to let us add a extra validation step. We check if the user is bot or human inside this filter. If its human we return empty error object else we add a add to the error object and return it.

Add No Captcha reCaptcha to the Lost Password Form

We need to integrate reCaptcha in admin lost password form to prevent bots from submitting this form. Here is the code to integrate it on admin lost password form:

function verify_lostpassword_captcha() {
	if (isset($_POST['g-recaptcha-response'])) {
		$recaptcha_secret = get_option('captcha_secret_key');
		$response = wp_remote_get("https://www.google.com/recaptcha/api/siteverify?secret=". $recaptcha_secret ."&response=". $_POST['g-recaptcha-response']);
		$response = json_decode($response["body"], true);
		if (true == $response["success"]) {
			return;
		} else {
			wp_die(__("<strong>ERROR</strong>: You are a bot"));
		}
	} else {
		wp_die(__("<strong>ERROR</strong>: You are a bot. If not then enable JavaScript"));
	}
	return $errors;    
}
add_action("lostpassword_form", "display_login_captcha");
add_action("lostpassword_post", "verify_lostpassword_captcha");

Let’s see how the above code works:

  • We displayed the check box using lostpassword_form action.
  • Before producing the final password reset link WordPress runs the lostpassword_post action to let us add a extra validation step. We check if the user is bot or human inside this filter. If its human we return nothing else we kill the script with an error message.

Final Thoughts

Google No Captcha reCaptcha

Its a new way to protect your website forms from bots and increase user friendliness. You can also learn how Google detects bots internally using this new type of captcha. Once you have integrated this plugin in your WordPress site write your experiences below.

About the Author
Narayan is a web astronaut. He is the founder of QNimate. He loves teaching. He loves to share ideas. He is a full-stack developer focusing on JavaScript, WordPress, Blockchain, DevOps, Serverless and Cordova. When not coding he enjoys playing football. You will often find him at QScutter classes. You can find him on Twitter as narayanprusty.
Wizard’s SQL for WordPress: Over 300+ recipes! Check the Demo »

16 responses to “Integrating Google No Captcha reCaptcha In WordPress Forms”

  1. Nice tutorial! Have you seen any user prompts that might be more widely understood than “I’m not a robot?” That kind of language has always bothered me for being nonsensical and likely confusing to people who have never seen it before.

  2. Matt McDowell 2015/01/20 3:38 pm

    @Dan I’ve also been thinking a lot about this. So far the best I’ve seen is something like “help us prevent spam – [do the following]”. Concise, explains the rationale, and (maybe) establishes common ground – we all hate spam.

  3. That makes sense, but even if you specify “comment spam” people who have never dealt with the backend of their own comment system may not realize what it is. Also, checking the box is actually required to post a comment, and the phrase “help us” suggests it is voluntary. Maybe “I promise this is not spam” + checkbox and a “what is this?” tooltip for a longer explanation? What happens if you don’t check the box and click submit? That is definitely where you need to provide some guidance for the perplexed.

    • Matt McDowell 2015/01/21 10:25 pm

      Good point. I’m thinking a tooltip or link below is probably the way to go. And maybe form validation with a more specific error message like “you must check this box to post your comment”.

      Looks like the current ReCAPTCHA error text is “Please verify that you are not a robot.” Could be better?

      Always worth (re)considering verbiage for the less savvy.

  4. Very useful, Jeff, thank you.

  5. Good article, I need to recode captcha with this approach.thanks

  6. Very informative tutorial, Narayan. Thanks for sharing.

  7. Gary Robinson 2015/02/05 5:58 am

    A very useful post for implementation, thanks. I’ve actually added the reCAPTCHA to a site and whilst it was great at addressing the spam it actually had a serious negative effect on conversions.

    As @Dan said, I think the wording is an issue. I also think the appearance is problem – it looks like a banner.

    I wrote up my experience of the test we ran, including the 74% loss in conversions. If this blog allows it, here is the link if anyone is interested.

    I do think the new version of reCAPTCHA will work – particularly with certain tech-savvy audiences – but I strongly recommend you monitor results as soon as it goes live and be prepared to roll it back.

    • You’re right, the logo and checkbox are even more confusing than the wording.

  8. Awesome! Thanks for sharing Narayan!

  9. Hi,
    First thank you so much but i have a problem im WP Comment Forms. Everbody sees that. How can i do showing captcha only guests?

    • Hi Serhat,

      Check out is_user_logged_in(), which can be checked before displaying the captcha. More infos here.

      • Thanks for your reply but I can’t this. My PHP skill so bad. Can you help me? Thanks.

      • Have you tried Google? There should be plenty of tutorials on how to implement. (I would help but I am overloaded with work)

      • Yes i tried. I getting some errors. For exp. I’m log out and write a comment then click sent comments button (robot box isn’t checked) and i get white page. No errors, only white page.

      • Yeah maybe ask your developer to help you, that way you know for sure.

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Wizard’s SQL for WordPress: Over 300+ recipes! Check the Demo »
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.