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/.