Add Google reCAPTCHA to WordPress Comment Form without Plugin

22 May 2024 by
Rakesh Chavada

Google reCAPTCHA is the easiest option to add CAPTCHA functionality to the website. Mostly, the CAPTCHA feature is used in the HTML form to protect from spam submission. In reCAPTCHA v2, a checkbox widget is added to the form and the user needs to check it to process the request. The user’s response is validated with reCAPTCHA API and the request is processed further. You can integrate the Google reCAPTCHA v2 checkbox with PHP easily in the web form.

There are various plugins available to integrate reCAPTCHA v2 checkbox in WordPress. If you want complete control in the reCAPTCHA widget and add Google reCAPTCHA without using any plugins, it can be done easily with manual integration. In this tutorial, we will show you how to add Google reCAPTCHA to WordPress comment form without plugin.

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

Create reCAPTCHA v2 API Keys

Before getting started register reCAPTCHA v2 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 v2 » I’m not a robot Checkbox
  • Domains – Specify the domain of your website.

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

Load reCAPTCHA JavaScript API

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

  • If the active theme of your WordPress site is Twenty Twenty-Two, edit the single.php file from the wp-content/themes/twentytwentytwo directory.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

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, specify the Site Key in the data-sitekey attribute.
  • In the is_valid_captcha_response() function, specify the Secret Key in the secret key of the $captcha_postdata array.
/** 
 * 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 select 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');
}

That’s it, the reCAPTCHA checkbox widget will be added to the comment form throughout the WordPress site.