fbpx

How to protect WordPress comment form from spam with Google reCAPTCHA V3


How to protect WordPress comment form from spam with Google reCAPTCHA V3

WordPress sites are often the target of unwanted spam comments. At the same time, this spam can compromise the quality of discussions and affect the credibility of the site. To counter this, many platforms use protection systems such as Google reCAPTCHA V3. In this article, we will explore how to integrate and configure Google reCAPTCHA V3 to effectively protect WordPress comment form from spam.

Understanding Google reCAPTCHA V3

Google reCAPTCHA V3 is an advanced security solution that uses a user behavior-based approach to detect and filter malicious bots. Unlike previous versions, reCAPTCHA V3 works in the background, evaluating user behavior without requiring direct interaction, improving the user experience.

Steps to integrate Google reCAPTCHA V3 into WordPress

To protect your comment forms against spam, you have several steps to follow which we will see below.

1. Obtain reCAPTCHA V3 API keys

In order to have the reCAPTCHA v3 API identifiers, you must follow the steps below:

  • Go to the Google reCAPTCHA website and log in with your Google account.
  • Create a new website and choose reCAPTCHA V3 type.
  • Get the public and private API keys generated for your site.

We recommend this article which better explains how to generate identifiers . How to protect WordPress comment form from spam with Google reCAPTCHA V3

2 – Choose the configuration option that suits you.

To add reCAPTCHA v3 to your comment form, you have two options:

  • Use a plugin (There are several, in our case, we will talk about the “reCAPTCHA for WordPress” plugin)
  • Develop yourself directly from your WordPress theme (If you have any knowledge of web programming)

Using the “reCAPTCHA for WordPress” Plugin

For a faster approach, a plugin can allow you to add reCAPTCHA v3 to your comment forms in seconds. Please proceed with caution when using plugins. Indeed, an extension can bring several problems. To know :

  • Security breaches. If the owner of the plugin does not maintain this, you can, for example, face the consequences.
  • The performance. A plugin can sometimes cause performance issues. In particular by adding additional CSS and JS to your website.
  • Website management. If you use, for example, a lot of plugins, managing them can become complex.

It is important to note, however, that plugins make life very easy by allowing you to have what you want as quickly as possible. That said, here are the steps

Install and Activate the reCAPTCHA Plugin

  • Go to your WordPress site dashboard.
  • In the menu, go to “Extensions” > “Add New”.
  • Search for the “reCAPTCHA for WordPress” plugin and install it.
  • Activate the plugin after installation.

Configure the reCAPTCHA Plugin

  • Go to “Settings” > “reCAPTCHA” in the dashboard.
  • Enter your public and private API keys in the corresponding fields.
  • Choose version V3 of reCAPTCHA.
  • Configure other options according to your preferences.

Integrate reCAPTCHA into the Comment Form

  • In the dashboard, go to “Appearance” > “Editor” and open the comment template file (comment.php).
  • Embed the reCAPTCHA code provided by the plugin in the appropriate place in the comment form.

Schedule the addition of reCAPTCHA v3 in your WordPress theme

When you have web programming skills, coding is usually ideal. In fact, it allows you to better maintain your web solution and minimize risks. However, it is important to understand that it is not for everyone. If you want to work with experts for reCAPTCHA implementation, contact us . You will partially follow the recommendations in this tutorial. How to protect your website against spam with Google ReCAPTCHA V3 or V2 [PHP + WordPress Extension] Namely:

  • Registering your website on the Google reCAPTCHA platform
  • Step 2 – Adding parameters to the form and managing data on the client side.

Add reCAPTCHA form fields to your contact forms.

WordPress offers a filter to add additional fields to the comment form. To do this, you must use the “comment_form” filter. To add the reCAPTCHA field to your website, you must use a function similar to this.


<?php 
function add_custom_fields_to_comment_form() {
    echo '<input type="hidden" name="reponsecaptcha" id="recaptcha2" value="">';
}

add_action('comment_form', 'add_custom_fields_to_comment_form');
?>

Intercept comment before publishing in WordPress

The reCAPTCHA check will consist of intercepting the comment and validating that the user is not a robot before inserting it into WordPress. We offer code similar to this:


<?php 
function verifyRecaptcha($response) {
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_secret = get_field('recaptcha_secret', 'option');
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $recaptcha_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => $recaptcha_secret, 'response' => $response)));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $capcharespo = curl_exec($ch);

    if(curl_errno($ch)){
        // Handle error, log the error message
      //  error_log('CURL Error: ' . curl_error($ch));
        return false;
    }
error_log('recaptcha_secret: ' . $recaptcha_secret);
    curl_close($ch);
    $Reponse = json_decode($capcharespo, true);

    if(isset($Reponse['success']) && $Reponse['success'] === true && isset($Reponse['score']) && $Reponse['score'] >= 0.5) {
        return true;
    }

    // Log the error codes if verification fails
    if(isset($Reponse['error-codes'])) {
       error_log('reCAPTCHA Error: ' . implode(',', $Reponse['error-codes']));
    }
    return false;
}



function custom_spam_validation($commentdata) {
    // Check if the comment author has passed your spam test
     $comment_content = isset($commentdata['comment_content']) ? $commentdata['comment_content'] : '';
    $reponsecaptcha = isset($_POST['reponsecaptcha']) ? $_POST['reponsecaptcha'] : '';

   if (!verifyRecaptcha($reponsecaptcha)) {
        // If spam test fails, you can customize the response or just exit
        wp_die('Sorry, your comment did not pass the spam test.');
    }

  // Remove unwanted HTML tags from the comment content
    $comment_content = wp_kses($comment_content, array(
        'a' => array(
            'href' => array(),
            'title' => array(),
        ),
        // Add more allowed tags and attributes as needed
    ));

    // Update the comment content in $commentdata
    $commentdata['comment_content'] = $comment_content;
   
  /// $commentdata['comment_content']  = "test";
    // If spam test passes, return the comment data
    return $commentdata;
}

add_filter('preprocess_comment', 'custom_spam_validation');
?>
Note: preprocess_comment is a WordPress filter that allows you to intercept the comment before publishing. You can use it to prevent cybercriminals from sending spam to your website.

Conclusion

To protect your website from spam with a reCAPTCHA, you can either use a plugin or do it. If you need assistance, contact us .

Gilblas Ngunte Possi

Gilblas Ngunte Possi

Founder and Full-Stack Developer at Prositeweb.

My proficiency with modern tools and a keen analytical sense regarding information technology enable me to provide superior guidance in the development and implementation of your web solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *

Gilblas Ngunte Possi

Gilblas
Typically replies within an hour

Gilblas
Hi there👋

How can I help you?
1:40
Chat with Us