Add Google reCAPTCHA to WordPress comments without plugin

reCAPTCHA it’s a free anti-spam service offered by Google. Easy to use, effective, easy to implement it’s the most used captcha API. You can read more at https://www.google.com/recaptcha/intro/. Let’s add Google reCAPTCHA to WordPress comments and see how it works.

Tested on WordPress 4.9 with Twenty Seventeen theme.

1. Go to https://www.google.com/recaptcha/admin#list and register your website.

Register website to Google reCAPTCHA

2. View the “Site key” and “Secret key”  which will be used later in the code.

Google reCAPTCHA view keys

3. Edit single.php from your theme folder (in my example /wp-content/themes/twentyseventeen) and add the following code before get_header();

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

4. Edit functions.php, add the code from below with your site_key (line 5) and secret_key (line 15).

/**
 * Google recaptcha add before the submit button
 */
function add_google_recaptcha($submit_field) {
    $submit_field['submit_field'] = '<div class="g-recaptcha" data-sitekey="your_site_key"></div><br>' . $submit_field['submit_field'];
    return $submit_field;
}
if (!is_user_logged_in()) {
    add_filter('comment_form_defaults','add_google_recaptcha');
}

/**
 * Google recaptcha check, validate and catch the spammer
 */
function is_valid_captcha($captcha) {
$captcha_postdata = http_build_query(array(
	            			'secret' => 'your_secret_key',
	            			'response' => $captcha,
	            			'remoteip' => $_SERVER['REMOTE_ADDR']));
$captcha_opts = array('http' => array(
	        		  'method'  => 'POST',
	        		  'header'  => 'Content-type: application/x-www-form-urlencoded',
	        		  'content' => $captcha_postdata));
$captcha_context  = stream_context_create($captcha_opts);
$captcha_response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify" , false , $captcha_context), true);
if ($captcha_response['success'])
    return true;
else
    return false;
}

function verify_google_recaptcha() {
$recaptcha = $_POST['g-recaptcha-response'];
if (empty($recaptcha))
    wp_die( __("<b>ERROR:</b> please select <b>I'm not a robot!</b><p><a href='javascript:history.back()'>« Back</a></p>"));
else if (!is_valid_captcha($recaptcha))
    wp_die( __("<b>Go away SPAMMER!</b>"));
}
if (!is_user_logged_in()) {
    add_action('pre_comment_on_post', 'verify_google_recaptcha');
}

5. No step five, that’s it!

15 Replies to “Add Google reCAPTCHA to WordPress comments without plugin”

  1. Is it possible to add a piece of code to disable the google captcha on comments if a user is logged into their account?

    This is fantastic though thank you!

    1. Hi Danny,
      Thank you for your feedback, I updated the code from functions.php, it shouldn’t appear when you are logged in.

      1. Is there any way to attach reCAPTCHA to my contact form as well? I can’t find in your code how you append the reCAPTCHA div to the submit button or elsewhere. But I’d like to protect my contact form via your method. Please, answer me asap. Thank you very much!

        1. You can attach reCAPTCHA in any form, but if you want to use the same method as I, you need to have two hooks in your form.

          1) Hook “add_google_recaptcha” into “comment_form_defaults”, which will display the reCAPTCHA.

          if (!is_user_logged_in()) {
          add_filter(‘comment_form_defaults’,’add_google_recaptcha’);
          }

          2) Hook: “verify_google_recaptcha” into “pre_comment_on_post” , which will validate the captcha.

          if (!is_user_logged_in()) {
          add_action(‘pre_comment_on_post’, ‘verify_google_recaptcha’);
          }

          Note: “comment_form_defaults” and “pre_comment_on_post” are already defined in wordpress, but if you use a custom form, you need to write them properly, to display and check the reCAPTCHA.

        1. If everything it’s setup correctly and it shows up on Posts, you should just check “Allow comments” on your Page and it should work.

          1. I created a test Page and it’s working.
            You should check if your page loaded reCAPTCHA.
            Search for recaptcha/api.js and <div class=”g-recaptcha”.
            And also you could check in Developer Tools from Chrome or Firefox if you have errors.

  2. I really like the approach and would love to implement this in a page but can’t seem to find the right hooks. Could you perhaps help? I don’t want to enable comments on all pages. What hooks should I be looking at and is it possible to enable it on a single page (and not others)?

Leave a Reply

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