How to Add reCAPTCHA to WordPress Comment (without Plugin)

Spam comment remains a problem for many WordPress users which utilize its commenting feature to interact with their visitors. For instance, some of us may expect to use the commenting feature as a medium to promote our products or provide technical support in certain cases, but we may often get irrelevant spam comments which may lead other users to become victims of cybersecurity attacks.

Adding reCAPTCHA to your WordPress commenting feature may help you prevent those spam comments from showing up on your website. The reCAPTCHA can provide protection against spam or abuse caused by bots by mitigating them using an advanced risk analysis engine and adaptive CAPTCHAs therefore only valid users can post comments on your website.

This tutorial will show you how to add reCAPTCHA to your WordPress commenting feature to filter out bots from spamming your website comments without involving any plugin.

Adding reCAPTCHA to WordPress Comment

Step 1: Setup the reCAPTCHA

Before you can use the reCAPTCHA, you need to set up it first. Start by visiting the Google reCAPTCHA site and then click on the V3 Admin Console (previously Admin Console). If you are logged in to your Google account, you will be directly taken to the reCAPTCHA registration page otherwise you’ll be asked to log in first.

On the registration page, you’ll need to fill out all the required fields and options to get a Site Key and a Secret Key like follows:

  • Start by adding a Label
  • select the reCAPTCHA v2 (to verify using an “I’m not a robot” challenge)
  • Add your website Domains (wppagebuilders.com for example)
  • Tick the checkbox to Accept the reCAPTCHA Term of Service
  • Click the Submit button to finalize the setup and get your reCAPTCHA key

Once you’ve got the keys, let’s start adding reCAPTCHA to your WordPress comment.

Step 2: Adding the reCAPTCHA Code to the Theme Files

The next step is adding the code snippets to your theme files to enable the reCHAPTCHA on your site. Before you start adding the snippets to your theme files, you may want to back up your site and use a child theme to avoid breaking the parent theme or losing your changes when you update your theme. Alternatively, to safely add custom code to your WordPress theme, you can use the code snippet plugin as it is an easier and faster way to add custom codes and manage them.

There are two files from the theme we need to add the code snippet for, the single.php file and the functions.php file. Once you’re ready, navigate to Appearance Theme File Editor then click single.php from the Theme Files to open the file editor to add the following snippet after the get_header(); line.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

The above snippet is to load the reCAPTCHA api.js from google. Once you’ve added the snippet, save the changes made to the file by clicking the Update File button.

Continue by selecting the functions.php file from the Theme Files list to add the following code at the bottom of the file editor.

/** 
 * Google reCAPTCHA: Add widget before the submit button 
 */ 
function add_google_recaptcha($submit_field) { 
    $submit_field['submit_field'] = '<div class="g-recaptcha" data-sitekey="Your_reCAPTCHA_Site_Key"></div>'.$submit_field['submit_field']; 
    return $submit_field; 
} 
 
if (!is_user_logged_in()) { 
    add_filter('comment_form_defaults', 'add_google_recaptcha'); 
} 
 
/** 
 * Google reCAPTCHA: verify response and validate comment submission 
 */ 
function is_valid_captcha_response($captcha) { 
    $captcha_postdata = http_build_query( 
        array( 
            'secret' => 'Your_reCAPTCHA_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(!empty($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><b>Please click the captcha checkbox.</b><p><a href='javascript:history.back()'>« Back</a></p>")); 
    }elseif(!is_valid_captcha_response($recaptcha)){ 
        wp_die(__("<b>Sorry, spam detected!</b>")); 
    } 
} 
 
if (!is_user_logged_in()) { 
    add_action('pre_comment_on_post', 'verify_google_recaptcha'); 
}

Before you go save the changes you made, you’ll need to add your Site Key and Secret Key from step 1 to the code as follows:

  • Add your Site Key to the data-sitekey from the $submit_field variable
  • Add your Secret Key to the secret from the $captcha_postdata array

And once you’ve added the two keys you can proceed to save the changes you made to the file by clicking the Update File button.

Step 3: Try the Comment with reCAPTCHA Activated

After you did all the previous steps, now you just need to try to comment as a visitor as the CAPTCHA challenge won’t appear if you are logged in.

As you can see from the above image, the “I’m not a robot” challenge is just above our comment button. To post a comment, the visitor needs to pass the challenge first before they can post it.

The Bottom Line

Adding reCAPTCHA to your WordPress commenting feature helps you prevent spam comments by providing protection against spam or abuse caused by bots using an advanced risk analysis engine and adaptive CAPTCHAs therefore only valid users can post comments on your website. This tutorial shows you how to add reCAPTCHA to your WordPress commenting feature to help you filter out bots from spamming your website comments. And to help you further on stopping spam comments, you can read our previous article about stopping spam comments in 8 simple ways and removing the website field from comments.

This page may contain affiliate links, which help support WP Pagebuilders. Learn more

Leave a Comment

Pin It on Pinterest

Thanks for commenting

Help us grow by sharing this post with your friends!

10+ free Elementor landing page templates. No extra plugin!

Creating with WordPress?​

Subscribe and join 1,500+ WordPress users receiving tips and insights on creating with WordPress in the no-code era. At WP Pagebuilders, we write about the following topics a lot.