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 (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

61 Comments

    1. for me also its not working. Google captcha code not display. but when i click on post comment button error message display “please check the captcha”

    2. Hello. Have you find the way to make the verification? Im in that same point, but useless if you are able to send the info without verification. Thanks in advance

  1. Hi, I have a problem. I did everything as explain, but when commenting, says it is wrong. Could you help me? The page is discussed, and test inputs there can be used as examples. From already thank you very much!

  2. Eugenio

    April 15, 2015 — 8:32 pm

    Hi, I have a problem. I did everything as explain, but when commenting, says it is wrong. Could you help me? The page is discussed, and test inputs there can be used as examples. From already thank you very much!

    Reply

    Shahid Shaikh

    April 15, 2015 — 9:03 pm

    Could you explain more please ! i mean exact error and on which phase.

    He says that the captcha doesnt work, because, when he check the box verifying that he’s not a robot, and tries to send the message, an alert shows saying: por favor ayudanos a verificar que no eres un robot(please help us verify that you are not a robot)

  3. I don’t have or see the options of the notes in funtions.php. Where i paste the code to put below the text field the captcha?

  4. Hello,

    How to add it on the login and registration page?

    I think discussing this is really important.

    Thanks

      1. Its a good alternative, but, making it by this way you dont charge another plugin to the site, its a “light way” to do it

  5. Very cool and I’m almost there but it isn’t working. When I test it, I get “http://johngirdwood.com Please Don’t spam” box after I do the captcha and submit a comment. Any idea where I’ve goofed? – JG

      1. Thanks for the reply. I’ve got it working now on one site and the initial issue seems fixed (I think it was just my coding error). But, now my other site is not requiring the reCAPTCHA. In other words, the box is there and everything but comments can be submitted without checking the box. Any ideas on where I messed up this time? Thanks again, John G.

  6. Good morning.
    I am working with java , the function jquery for validate captcha before from make clic en the button save how would be ?
    excuse my english level.

  7. Hello Shahid. So far this is the best tutorial explanation for this integration with Google reCaptcha without using any wp plugin. So thanks a lot.
    From here I was able to use this in my page template which has a form integrated to my CRM platform.
    The only part im stuck, is in the validation. My form submits anyway even if I havent unchecked the box “Im not a robot”
    Could you give me some guidance on how to achieve that please?
    Thanks in advanced

    1. Hey diana,

      Thanks for posting comment.

      If you visit demo http://demo.codeforgeek.com/google-captcha/ and try to fill the form without checking the google captcha checkbox, you will receive an error right after form gets submit. It’s Server side validation. Are you sure you are using same code or not missing the following code in the file where forms submission happen ?

      if(isset($_POST['g-recaptcha-response'])){
         $captcha=$_POST['g-recaptcha-response'];
      }
      if(!$captcha){
         echo '<h2>Please check the the captcha form.</h2>';
         exit;
      }
      1. That live form does not work either. After you submit the form it says “Please check the the captcha form.”

  8. Thanks for your answer Shahid…right before to came to see the answer what I did was to change de var data_2 replacing it by data, in the code that belongs to the single.php (In my case is a page template) assuming the variable passing in the google_captcha.php was data
    In single.php
    ` var data;
    jQuery.ajax({
    type: “POST”,
    url: “http://trackitgb.staging.wpengine.com/wp-content/themes/customizr-child/google_captcha.php”,
    data: jQuery(‘__vtigerWebForm’).serialize(),
    async:false,
    success: function(data) {
    if(data.nocaptcha===”true”){
    data=1;
    }else if(data.spam===”true”)
    {
    data=1;
    }
    else
    {
    data=0;
    }
    }
    });

    if(data!=0){
    e.preventDefault();
    if(data==1){
    alert(“Please check the captcha”);
    }else{
    alert(“Please Don’t spam”);
    }
    }else
    {
    jQuery(“#__vtigerWebForm”).submit
    }
    }); `

    and the code of google_captcha.php satys as you suggested.
    No the page triggers the alert “please dont spam” but i went to check the google box and again the alert on spam remain…
    So what Im misssing?

    Thanks in advance

      1. Im sorry but im not so good with jquery….so what is what I need to change and where exactly?
        Sorry for all this, and you have to know that I really appreciate your answers!

  9. Hello There. I discovered your weblog the use of msn. That is a really neatly written article.
    I will be sure to bookmark it and come back to read more of your useful info.
    Thank you for the post. I’ll definitely comeback.

  10. Hi there,

    I followed your tutorial step-by-step but when i click on post comment button I continue get error message display “please check the captcha”

    I put Google captcha site key in code. ( Followed what’ve said step-by-step).

    So What I can do?

  11. Hi Guys, does this recaptcha work? I cant get past the (Please Don’t spam) popup part am I missing something. I need this recaptcha for a custom register form there are no plugins that work with it at all, any help regarding this recaptcha will be helpful, thanks

      1. Hi Shahid
        I am trying to add the recaptcha to wordpress, so far it seems to work well with the comments form but the submit is not passing the popup that stats (Please Don’t spam), I am not sure if I am missing something, thanks for your quick response.

        1. I think i have done something wrong in single.php code.

          Can you try this code ?

          <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") {
                        e.preventDefault();
                        alert("Please check the captcha");
                      } else if(data.spam==="true") {
                        e.preventDefault();
                        alert("Please Don't spam");
                      } else {
                        jQuery("#commentform").submit
                      }
                  }
              });
            });
          </script>

          Let me know if it works, if it does will update the code in blog post.

  12. Hi, no it is not working with the comments form now, you can view it here: http://www.satourismdirectory.co.za/mpumalanga/hotels/indawo-game-ranch-hotel/

    It throws out these errors now:

    Error: ReCAPTCHA placeholder element must be empty
    …t does not exist”);if(!Ya(fe(c)))throw Error(“ReCAPTCHA placeholder element must…

    https://www.gstatic.com/recaptcha/api2/r20160119135516/recaptcha__en.js

    8:11:28.713 CSI/tbsd_
    8:11:28.714 CSI/_tbnd
    NetworkError: A network error occurred.

  13. Hi, yes I did change the link:
    url: “http://www.satourismdirectory.co.za/wp-content/themes/directory2/portal/functions/google_captcha.php”,

  14. Hi, I have added the old code but I notice now that the same error occurs with it as well, do you thing it is conflicting with a plugin that might be part of the directory2 theme? I am not to sure it is my first time working with this theme coding all over the place.

  15. The form name is the same and the button,
    but I am not too sure about the functions.php now this could be completely different add_filter(‘comment_form’,’add_google_captcha’);

    This is how the code is written for this theme:

    [code]
    {if $post->hasComments}
    {__ ‘Comments (%s)’|printf:$post->commentsNumber}

    {loopComments as $comment}

    {if !$comment->isNormal}

    htmlClass} {!$comment->htmlId(‘li-‘)}>
    {capture $editLinkLabel}({__ ‘Edit’}){/capture}
    {__ ‘Pingback:’} {!$comment->author->link} {!$comment->editLink($editLinkLabel)}

    {else}

    htmlClass} {!$comment->htmlId(‘li-‘)}>
    htmlId} class=”comment-article”>

    {!$comment->author->avatar(58)}

    {!$comment->author->link}
    url}”>time(c)}”>{_x ‘%1$s at %2$s’, ‘1: date, 2: time’|printf: $comment->date, $comment->time}

    {capture $replyLinkLabel}{!__ ‘Reply’}{/capture}
    {!$comment->replyLink($replyLinkLabel)}
    {capture $editLinkLabel}{!__ ‘Edit’}{/capture}
    {!$comment->editLink($editLinkLabel)}

    {if !$comment->isApproved}
    {__ ‘Your comment is awaiting moderation.’}
    {else}
    {!$comment->text}
    {/if}

    {* there is no tag, it is handled by comment walker class *}
    {/if}
    {/loopComments}

    {if $post->willCommentsPaginate}

    {__ ‘Comment navigation’}
    {prevCommentsLink ‘← Older Comments’}
    {nextCommentsLink ‘Newer Comments →’}

    {/if}

    {if $post->hasCommentsClosed}
    {__ ‘Comments are closed.’}
    {/if}
    {/if}

    {commentForm}
    [/code]

  16. Hi Shahid, I have managed to get rid of the Error: ReCAPTCHA placeholder element must be empty error, this was cursed by two api’s from google, but I still cant get past the (Please Don’t spam) popup, thanks for your help.

  17. Hi, I just added the code but it is not assigning to the form, I have added it to the register form now this is where I need the recaptcha to be tons of fake registrars.

  18. Hi, thank you!!!

    For the last two examples there is a problem in function snippet where:
    add_filter(‘comment_form_defauls’,’add_google_captcha’);

    comment_form_defauls is a misspelled hook name the right one is comment_form_defaults

    with the right name it’s working fine.

  19. Hi Shahid! Thanks a lot for your post! Can you please just update it according to the change in single.php? It also hadn’t worked for me till I read the comments. Thank you.

  20. Thanks for this – great post! I have noticed one issue though and I’m wondering if it is caused by these customisations. When I post a comment, I get taken to wp-comments-post.php and shown an error: please fill the required fields (name, email).

    One way around this is to make these fields optional, but even in this case, I also notice that when they are filled in the comment is still posted as “Anonymous” which makes me think that these form fields aren’t being parsed.

    Can you think of a solution to this issue?

  21. Fantastic website. Lots of useful info here. I am sending it to a
    few buddies ans additionally shaaring in delicious. And obviously, thanks for your sweat!

  22. Hello Mr. Shahid

    First of all, thank you for your efforts

    I get this error when i try to open a single post page

    “Parse error: syntax error, unexpected ‘<' in /home/tethkarwaxfra/public_html/wp-content/themes/musikal/single.php on line 17"

    Can you help please what could be the problem ?

    I checked your above posts and I'm sure I did as you explained, still not fixed

    Maybe there is a name related to your template/path I didn't change

    Looking forward to hear from you

    Thank you

      1. and anybody can send you spam, your cod can’t defense from spam , need add check in php code when send comment use action filter ‘preprocess_comment’ , there making check and if correct return ahead comment if not return null and comment not add to data base, but your code like example . I think your code useless for site, but maybe I badly know 🙂 ,

        this including can’t help against bots , offed javascript and can send any spam

  23. Thank you so much for this example.
    response code should be change as below,

    $response=file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=Your secret key&response=”.$captcha.”&remoteip=”.$_SERVER[‘REMOTE_ADDR’]);
    $response = json_decode($recaptcha_response);

    // validating result.
    if ($recaptcha_response->success == false) {
    $data=array(‘spam’ => ‘true’);
    echo json_encode($data);
    } else {
    $data=array(‘spam’ => ‘false’);
    echo json_encode($data);
    }

  24. Hi I have installed recaptcha on my wordpress site and it works fine except for the following issue; when you hit “send” the contact form doesn’t clear and the message “your message was sent successfully” does not appear at all, even though I get the emails. When I remove the BWPress reCAPTCHA from the contact form it works fine. Any solutions as I get quite a bit of spam as it is? Thanks.

  25. Thanks for the example. I was building the exact same when I needed to confirm how the server side was called from jQuery and this was spot on.

Leave a Reply

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