reCAPTCHA v2 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 and reCAPTCHA v2.
1. Go to https://www.google.com/recaptcha/admin#list and register your website.
2. View the “Site key” and “Secret key” which will be used later in the code.
3. Edit single.php from your theme folder (in my example /wp-content/themes/twentyseventeen) and add the following code before get_header();
<br> wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js');<br>
4. Edit functions.php, add the code from below with your site_key (line 5) and secret_key (line 15).
<br> /**<br> * Google recaptcha add before the submit button<br> */<br> function add_google_recaptcha($submit_field) {<br> $submit_field['submit_field'] = '<div class="g-recaptcha" data-sitekey="your_site_key"></div><br>' . $submit_field['submit_field'];<br> return $submit_field;<br> }<br> if (!is_user_logged_in()) {<br> add_filter('comment_form_defaults','add_google_recaptcha');<br> }</p> <p>/**<br> * Google recaptcha check, validate and catch the spammer<br> */<br> function is_valid_captcha($captcha) {<br> $captcha_postdata = http_build_query(array(<br> 'secret' => 'your_secret_key',<br> 'response' => $captcha,<br> 'remoteip' => $_SERVER['REMOTE_ADDR']));<br> $captcha_opts = array('http' => array(<br> 'method' => 'POST',<br> 'header' => 'Content-type: application/x-www-form-urlencoded',<br> 'content' => $captcha_postdata));<br> $captcha_context = stream_context_create($captcha_opts);<br> $captcha_response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify" , false , $captcha_context), true);<br> if ($captcha_response['success'])<br> return true;<br> else<br> return false;<br> }</p> <p>function verify_google_recaptcha() {<br> $recaptcha = $_POST['g-recaptcha-response'];<br> if (empty($recaptcha))<br> wp_die( __("<b>ERROR:</b> please select <b>I'm not a robot!</b><p><a href='javascript:history.back()'>« Back</a></p>"));<br> else if (!is_valid_captcha($recaptcha))<br> wp_die( __("<b>Go away SPAMMER!</b>"));<br> }<br> if (!is_user_logged_in()) {<br> add_action('pre_comment_on_post', 'verify_google_recaptcha');<br> }<br>
5. No step five, that’s it!
Update: You can check our reCaptcha v3 post, https://www.oueta.com/wordpress/add-google-recaptchav3-to-wordpress-comments-without-plugin/.
Thanks! I add this on my site and now 0% spam 🙂
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!
Hi Danny,
Thank you for your feedback, I updated the code from functions.php, it shouldn’t appear when you are logged in.
Hey man! You’re awesome! This method works for me! Thank you for clean code!
Hi Alex, thank you for your feedback.
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!
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.
Hi,
I’m almost there (I think). How do I get this on the login page? I’m using the login_form filter and action hooks by adding them to the ‘login_form’ but when I add those below the comment form in the functions.php it looks like this.
http://dev.euhsd.org/wp-login.php?redirect_to=http%3A%2F%2Fdev.euhsd.org%2Fwp-admin%2F&reauth=1
BTW – I added the wp_enqueue_script to the wp-login.php
Thank you for any suggestions.
Thanks for this great tutorial but I have some problem please check this link for the screenshot https://i.imgur.com/A2BTcXF.png I want to move this box down in the button as this captcha is hiding my text
Hi Suraj,
Try to put your additional elements in DIV’s.
Thank you for replying. And one more problem, Captcha is not showing on Pages. Please, can you assist me regarding this?
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.
I’m not a Robot is working fine in posts but doesn’t in the page, you I have enabled it in my pages. Can you please check the screenshot
https://i.imgur.com/JilzXtx.png In this screenshot I can’t find captcha but in the second screenshot https://i.imgur.com/IXLfRq2.png it’s showing error.
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.
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)?
Hi Ed,
When you add a new Page, you should have a checkbox with “Allow comments”.
Hello,
I have used your tutorial and seem to always get rejected by the recaptcha.
I pasted the code into functions at the end. and used my key and code.
Everything dispays correctly on the site just keeps rejecting the comments.
Any help would be apreciated.
Hi,
Try to register a new key..
Hello are you able to show me how to handle the error message on the same page instead of a redirect? Thank you for the help btw.
Sorry, it won’t work for me. I’ve placed the code in the appropriate place (top) in “singles.php”, placed the code and the 2 keys in their respective places in “functions.php” but, no go. I can’t even see it! Before I tried your code, I tried it with a Google reCaptcha plugin which kept giving me an error and wouldn’t let me sign in. Deactivating it solved the problem. I have changed keys 3 times and I don’t know what else to do. Think you can help me?
Thanks
Rechecked, it seems the problem is the login (at least), where it’s not showing up. I can see it in the comments but only because, although I appear as loged in, as soon as I try to navigate within the site, I am loged out. Very strange!
Ok, I think I’ve understood the problem. The thing is that I have the “Ultimate Member” plugin installed which has its own login and registration pages. The code you are so kindly sharing, obviously does not include these pages. From reading around (I,m a newby, if you haven’t noticed :), I think what I need to do is to add hooks to those pages, which I know I don’t know how to do.
I have for the moment, implemented the plugin’s extension but I don’t like it as it isn’t v2 or v3 and gives that awfull image thingy which I personally, have always despised. It’ll have to do for the moment, however. So, I’ll keep searching and learning and if you can give me a hand, I’d deeply appreciate it. Cheers!
Hi Ioannis,
So far I tested this on “Twenty Seventeen” theme, I would test first this on a clean wordpress test setup.
When i added this code in function.php and just inter my site key and secret key it showing error. Below
Your PHP code changes were rolled back due to an error on line 370 of file wp-content/themes/bimber/functions.php. Please fix and try saving again.
syntax error, unexpected ‘ ‘ (T_STRING), expecting ‘)’
Also added code in single.php
Please provide any suggestion.
Hi Imran,
Please double check the syntax.
This is a great post. The code works, thanks
Great , this code work and i dont need to use a plugin
But i put all the code in snippet code instead of single.php or o file that handle post
Is there a way to enable the checkbox version other than the “select the image” version?
Please help me !
How can I add recaptcha in my wordpress defult login page without any plagin?
Please !
I hope you will help me.
Thanks Bro for simple and clean code and 100% woking
Thank you for your feedback
Hi OUETA, would it be different codes based on reCaptcha v2 checkbox / reCaptcha v2 invisible / reCaptcha v3 or the code is same for all versions, just the key and secret would be different? Also is your code is fully compliant with WordPress 5.5, I mean they changed some codex I heard, like how you enqueue scripts etc. Thanks in advance.
Hi Saidul,
Did you manage to find out if this code will work for the invisible reCaptcha V2?
Thanks!
Hi,
We have posted a tutorial for reCaptcha V3, https://www.oueta.com/wordpress/add-google-recaptchav3-to-wordpress-comments-without-plugin/