Creating Captcha for Contact Form in WordPress

A detailed guide on how to add Captcha to the contact form in WordPress to protect your website from spam and automated bots.

This article will guide you through the process of integrating Captcha into the contact form in WordPress using Google reCAPTCHA. We will go through the installation and configuration steps to ensure your site is secure.

PHP Code

To add Captcha to the contact form, you can use the following code in the functions.php file of your theme or a custom plugin:

// Add reCAPTCHA to contact form
function my_contact_form_captcha() {
    ?>
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
    <?php
}
add_action('wp_footer', 'my_contact_form_captcha');

// Handle Captcha verification
function verify_captcha($fields, $form) {
    if (isset($_POST['g-recaptcha-response'])) {
        $response = $_POST['g-recaptcha-response'];
        $remoteip = $_SERVER['REMOTE_ADDR'];
        $secret = 'YOUR_SECRET_KEY';

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = [
            'secret' => $secret,
            'response' => $response,
            'remoteip' => $remoteip
        ];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
            ],
        ];
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $resultJson = json_decode($result);
        
        if (!$resultJson->success) {
            // Handle when Captcha is invalid
            return new WP_Error('captcha_error', 'Please verify the Captcha.');
        }
    } else {
        return new WP_Error('captcha_error', 'Please verify the Captcha.');
    }
}
add_action('contact_form_before_send', 'verify_captcha', 10, 2);

Detailed explanation:

  1. my_contact_form_captcha(): This function adds the reCAPTCHA widget to the footer of the page; replace YOUR_SITE_KEY with your site key.
  2. verify_captcha(): This function handles Captcha verification after the user submits the form. It sends a request to Google to validate the Captcha code and processes the response.
  3. add_action('wp_footer', 'my_contact_form_captcha'): Adds reCAPTCHA to the footer section of WordPress.
  4. add_action('contact_form_before_send', 'verify_captcha', 10, 2): Calls the Captcha verification function before sending the contact form.

System Requirements:

  • WordPress 4.0 or higher
  • JavaScript-enabled browser

How to install the libraries needed to run the PHP code above:

  1. Register for an account at Google reCAPTCHA.
  2. Create a site key and secret key for your domain.
  3. Replace YOUR_SITE_KEY and YOUR_SECRET_KEY in the above PHP code.

Tips:

  • Consider using reCAPTCHA v2 or v3 for better security.
  • Double-check DNS settings if you encounter issues with Captcha verification.


Related

How to UPDATE data in a MySQL database of WordPress

A guide on how to use Prepared Statements in PHP to update data in the MySQL database of WordPress safely and effectively.
How to send Authentication Header Token when POSTing data to API from WordPress

A guide on how to send data to an API from WordPress using the POST method and pass an Authentication Header Token for security. This article provides detailed instructions on how to configure and send an HTTP request.
How to DELETE data from a MySQL database in WordPress

A guide on how to use Prepared Statements in WordPress to delete data from a MySQL database safely and effectively.
Step-by-step guide to creating Facebook OAuth login functionality in WordPress

A detailed guide on how to integrate Facebook OAuth login functionality in WordPress, covering steps from creating a Facebook Developer app to configuring a supporting plugin in WordPress.
Detailed guide on how to add Google OAuth login functionality in Wordpress

This article provides a detailed guide on how to integrate Google OAuth login functionality into Wordpress, allowing users to log in to your website using their Google accounts conveniently and securely.
How to INSERT data into a MySQL database in WordPress

A guide on how to use Prepared Statements in WordPress to safely and effectively insert data into a MySQL database.
Guide to Implement Apple OAuth Login in WordPress

A detailed guide on how to integrate Apple OAuth login into your WordPress site, including plugin installation and Apple OAuth service configuration.
How to Force HTTPS in WordPress

A step-by-step guide on how to force HTTPS in WordPress, ensuring that all traffic to your website is redirected to HTTPS, thus enhancing security and improving SEO.
A Comprehensive Guide to Creating a WordPress Plugin

This article provides a step-by-step guide on how to create a WordPress plugin, including the basic structure, coding, and installing the plugin. You will learn how to extend the functionality of your WordPress site through plugin development.
Complete Guide on How to Create a WordPress Theme

This article guides you step-by-step on creating a WordPress theme from scratch, including folder structure, necessary files, and how to customize the interface for your website.

main.add_cart_success