How to add Google reCAPTCHA in WordPress

Google reCAPTCHA is becoming popular since the day of its announcement. The performance of this product is not been evaluated yet because of its age.

I have covered basic tutorial about how to code custom script with Google reCAPTCHA.

In this tutorial i am going to explain how to add Google reCAPTCHA in WordPress engine. By using same method i added Google captcha in my blog. Have a look.

Screenshot from 2014-12-15 10:45:32

UPDATE : We have updated the theme design and removed google ReCaptcha to address site loading issue but it still works the way is explained below.

Step 1: Register your blog to Google reCAPTCHA.

First signup with your google account to Google reCAPTCHA site and register your blog here to get site key and secret key.

capcha1

Step 2: Add captcha in WordPress comment form.

WordPress made an awesome feature called “hooks” which allow us to insert custom code in WordPress. You can do same by adding code to the particular file. In this case file would be comments.php.

Open your functions.php and add these lines of code in end of bottom.

Where is functions.php located ?

Answer : function.php is placed in yoursite.com/wp-content/themes/theme_name/function.php. Better use filezilla to navigate and edit code properly.

functions.php
/*Add Google captcha field to Comment form*/

add_filter('comment_form','add_google_captcha');

function add_google_captcha(){
    echo '<div class="g-recaptcha" data-sitekey= "=== Your site key === "></div>';
}

/*End of Google captcha*/

Step 3: Add captcha verification script.

Open single.php from your theme main folder. This file is responsible for showing single post in your site. Since comment will be visible in posts ( if on page too then add those page code too) we need to add our extra verification which is Google recaptcha verification.

Add following lines of code before the end of get_footer();.

single.php
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
jQuery("#submit").click(function(e){
        var data_2;
    jQuery.ajax({
                type: "POST",
                url: "http://yourblog.com/wp-content/themes/yourtheme/google_captcha.php",
                data: jQuery('#commentform').serialize(),
                async:false,
                success: function(data) {
                 if(data.nocaptcha==="true") {
               data_2=1;
                  } else if(data.spam==="true") {
               data_2=1;
                  } else {
               data_2=0;
                  }
                }
            });
            if(data_2!=0) {
              e.preventDefault();
              if(data_2==1) {
                alert("Please check the captcha");
              } else {
                alert("Please Don't spam");
              }
            } else {
                jQuery("#commentform").submit
           }
  });
</script>

Now we have added code to verify our captcha form. Here is PHP script which is responsible for calling Google API to determine the Spammer. create file and place code shown below and put it inside the theme folder and change path in above JavaScript code.

google_captcha.php
<?php
    $data;
    header('Content-Type: application/json');
    error_reporting(E_ALL ^ E_NOTICE);
    if(isset($_POST['g-recaptcha-response'])) {
      $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
      $data=array('nocaptcha' => 'true');
      echo json_encode($data);
      exit;
     }
     // calling google recaptcha api.
     $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=Your secret key&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
     // validating result.
     if($response.success==false) {
        $data=array('spam' => 'true');
        echo json_encode($data);
     } else {
        $data=array('spam' => 'false');
        echo json_encode($data);
     }
?>

This is it. Open your posts and you should able to see Google reCAPTCHA after comment form.

Further enhancement:

I want Google captcha after email field ?

To do this you need to add following line of code in function.php instead of the one mentioned above.

functions.php
add_filter('comment_form_defaults','add_google_captcha');

function add_google_captcha( $default ) {
    $default[ 'fields' ]["email"] .= '<p class="google-captcha-form">' .
        '<label for="Google captcha">'. __('Captcha') . '</label>
        <span class="required">*</span>
        '
<div class="g-recaptcha" data-sitekey=" Your site key "></div>;
    return $default;
}

I want Google captcha after comment textarea ?

Well this is tricky, WordPress have no such hook but there is one way to do it. WordPress allows to add Notes after textarea which is comment box. Instead of notes we can show our captcha there. Here is how to do so.

functions.php
add_filter('comment_form_defaults','add_google_captcha');

function add_google_captcha($default) {
    $default['comment_notes_after']='<div class="g-recaptcha" data-sitekey=" site key"></div>';
    return $default;
}

Here is proof of code.

Screenshot from 2014-12-15 11:39:50

Conclusion:

Google reCAPTCHA is really awesome program and you should give it a try. There are some WordPress plugin as well which let you add Google captcha easily. Do a Google and find it out.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126