Best way to add Google reCAPTCHA to WordPress Comment form

On Crunchify, we are using reCAPTCHA v2 on WordPress comment form.

There are multiple plugins available out there to achieve the same. In this tutorial we will go over steps on how to add Google reCAPTCHA without any plugin.

Let’s get started:

Steps are very simple:

  1. Login to Google reCAPTCHA and get Site key and Secret key.
  2. Enqueue and load Google reCAPTCHA API java srcript.
  3. Add google reCAPTCHA box to WordPress comment form.
  4. On WordPress comment form Submission, check for Google API response.
    • Based on the false response stop
    • Based on success response proceed with submission.

Step-1. Login and get Google reCAPTCHA credentials

  • Link: https://ift.tt/9SChg7I
Create Google reCAPTCHA account and create sitekey and secretkey

Step-2. Enqueue Google reCAPTCHA code

Let’s enqueue and load google reCAPTCHA API JavaScript. Just put below code into your WordPress theme’s functions.php file.

wp_enqueue_scripts: Fires when scripts and styles are enqueued.

add_action( 'wp_enqueue_scripts', 'crunchify_enqueue_scripts_styles' );
function crunchify_enqueue_scripts_styles() {
        wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js');
}

Step-3. Add Google reCAPTCHA checkbox to Comment form

Add Google reCAPTCHA to WordPress Comment form

Just put below code into your WordPress theme’s functions.php file.

/* Crunchify's Google reCAPTCHA code */

// This applies to only user who are not logged in. Admin wont see Google reCAPTCHA.
if (!is_user_logged_in()) {
        // pre_comment_on_post: this WordPress filter fires before a comment is posted.
        add_action('pre_comment_on_post', 'crunchify_verify_check_google_recaptcha');
}

function crunchify_verify_check_google_recaptcha() {
        
        // If empty google recaptcha response - then ask users to select Google reCAPTCHA checkbox and try again.
        if (empty($_POST['g-recaptcha-response']))
           wp_die( __("<b>ERROR:</b> Seems you haven't check I'm not a robot! Please select and try again.<p><a href='javascript:history.back()'>« Back</a></p>"));
        
        // If google says its not a valid captcha or feels like spammer then stop.
        else if (!crunchify_check_if_valid_captcha($_POST['g-recaptcha-response']))
           wp_die( __("<b>Hey.. Seems you are a SPAMMER!!!</b>"));
}

// This applies to only user who are not logged in. Admin wont see Google reCAPTCHA.
// comment_form_defaults: Filters the comment form default arguments.
if (!is_user_logged_in()) {
    add_filter('comment_form_defaults','crunchify_add_google_recaptcha_wordpress');
}

// Let's add Google reCAPTCHA on Comment Form
function crunchify_add_google_recaptcha_wordpress($submit_field) {
        
        // Pleaes make sure to replace your Site Key here
    $submit_field['submit_field'] = '<div class="g-recaptcha" style="overflow: hidden;" data-sitekey="123Lf-sokjAA34dJ9iu6-UA03M-h9EQd34@sD"></div>' 
                . $submit_field['submit_field'];
    return $submit_field;
}

// Verify if Captcha is good. Response from Google API
function crunchify_check_if_valid_captcha($crunchify_captcha) {
        
        // Pleaes make sure to replace your Secret Key here
        $crunchify_captcha_postdata = http_build_query(array(
                            'secret' => '123Lf-sokjAAA2323FSFQJqa3hYQlvpSyzBQWQ',
                            'response' => $crunchify_captcha,
                            'remoteip' => $_SERVER['REMOTE_ADDR']));
        $crunchify_captcha_opts = array('http' => array(
                      'method'  => 'POST',
                      'header'  => 'Content-type: application/x-www-form-urlencoded',
                      'content' => $crunchify_captcha_postdata));
        
        $crunchify_captcha_context  = stream_context_create($crunchify_captcha_opts);
        
        // json_decode: Decodes a JSON string
        // file_get_contents: Reads entire file into a string
        $crunchify_captcha_response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify" , false , $crunchify_captcha_context), true);
        if ($crunchify_captcha_response['success'])
                return true;
        
        else
                return false;
}

Please make sure to change your site keys in ab

And that’s it.


Step-4. Clear site cache and check it out

Try clearing your site’s cache and refresh page. You should see now Google reCAPTCHA added to your WordPress comment form as below.

How to add Google reCAPTCHA to WordPress Comment form without any Plugin

Let me know if you face any issue showing Google reCAPTCHA.

The post How to add Google reCAPTCHA to WordPress Comment form without any Plugin? appeared first on Crunchify.