Integrate Google reCAPTCHA v3 in WordPress Comment Form without Plugin

22 May 2024 by
Rakesh Chavada

Google reCAPTCHA v2 checkbox and v3 both are used for the same purpose, protecting websites from spam and bots. The main difference between reCAPTCHA v2 and v3 is that Google reCAPTCHA v3 does not interrupt the site users. So, the reCAPTCHA v3 can execute in any section of the webpage without affecting conversion. Google reCAPTCHA v3 returns a score for each request without user interaction. Based on the score, we can accept and block requests in the web application.

You can integrate Google reCAPTCHA v3 with PHP in web form or pages. If you want to integrate reCAPTCHA v3 in WordPress, there are various reCAPTCHA WordPress plugins are available to add Google reCAPTCHA v3 in the WordPress comment form. Alternatively, you can integrate Google reCAPTCHA v3 in WordPress without using any plugins for better control and customization. In this tutorial, we will show you how to integrate Google reCAPTCHA v3 in WordPress comment form without plugin.

Follow the below simple steps to integrate reCAPTCHA v3 into the comment form in WordPress.

Create reCAPTCHA v3 API keys

Before getting started register reCAPTCHA v3 keys on the Google reCAPTCHA Admin console.

Visit the reCAPTCHA admin console and register the domain of your website.

  • Label – It helps to identify your registered site in the future.
  • reCAPTCHA type – Select reCAPTCHA v3 (Verify requests with a score).
  • Domains – Specify the domain of your website.

On submission, the reCAPTCHA v3 Site Key and Secret Key will be generated. Note these keys which will be used later in the code.

Load reCAPTCHA API JavaScript library

Edit the single.php file of the active theme directory and add the following code before the get_header().

  • If the active theme of your WordPress site is Twenty Twenty-One, edit the single.php file from the wp-content/themes/twentytwentyone directory.
  • Use wp_enqueue_script() method to load reCAPTCHA API script.
  • Add the render parameter in the query string of the reCAPTCHA API URL and specify the Site Key.
wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js?render=YOUR_reCAPTCHA_SITE_KEY');

Note that: Replace YOUR_reCAPTCHA_SITE_KEY with your Google reCAPTCHA Site Key.

Add reCAPTCHA and Verify Response

Edit the functions.php file of the active theme directory and add the following code.

  • In the add_google_recaptcha() function, pass the Site Key in the first parameter of the grecaptcha.execute() method.
  • In the is_valid_captcha_response() function, specify the Secret Key in the secret key element of the $captcha_postdata array.
  • The Google reCAPTCHA verification API (https://www.google.com/recaptcha/api/siteverify) returns a score from 0.0 to 1.0 (0.0 is likely a bot, where 1.0 is very likely a valid interaction).
  • The comment request will proceed if the score is greater than 0.5.
/** 
 * Google reCAPTCHA: Add widget before the submit button
 */
function add_google_recaptcha($submit_field) {
    $submit_field['submit_field'] = '<p class="form-submit">
        <input type="submit" name="buttonSubmit" id="buttonSubmit" class="submit" value="Post Comment">
        <input type="hidden" name="comment_post_ID" value="'.get_the_id().'" id="comment_post_ID">
        <input type="hidden" name="comment_parent" id="comment_parent" value="0">
        <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
    </p>
    <script>
    document.getElementById("buttonSubmit").onclick = function onClick(e) {
        e.preventDefault();
        grecaptcha.ready(function() {
            grecaptcha.execute("YOUR_reCAPTCHA_SITE_KEY", {action: "submit"}).then(function(token) {
                document.getElementById("g-recaptcha-response").value = token;
                document.getElementById("commentform").submit();
            });
        });
    }
    </script>
    ';
    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($captcha_response['success'] && $captcha_response['score'] > 0.5){
        return true;
    }else{
        return false;
    }
}

function verify_google_recaptcha() {
    $recaptcha = $_POST['g-recaptcha-response'];
    if(empty($recaptcha)){
        wp_die(__("<p><strong>Error:</strong> Sorry, spam detected!</p><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');
}

Note that: Replace YOUR_reCAPTCHA_SITE_KEY and YOUR_reCAPTCHA_SECRET_KEY with your Google reCAPTCHA Site and Secret Keys.

That’s it! Now you will see the reCAPTCHA v3 verification functionality is added to the comment form throughout the WordPress site.