How to Add Google reCAPTCHA v2 to WordPress Forms

Add Google reCAPTCHA v2 to a WordPress form

Google reCAPTCHA v2, the “I’m not a robot” checkbox, stops most spam bots on contact, registration and comment forms. You need two keys from Google and two pieces of code: the widget in the form, and a check of its token on the server before the form is processed.

Problem: A custom WordPress form receives spam that passes a simple honeypot field.

Solution: Register the site in the reCAPTCHA admin console, load the reCAPTCHA script on the form page, add the g-recaptcha element to the form, and verify the g-recaptcha-response token with wp_remote_post() to Google’s siteverify endpoint in the form handler.

Keys

Register the domain at google.com/recaptcha/admin, choose reCAPTCHA v2 “I’m not a robot”, and copy the site key and the secret key into wp-config.php:

<?php
define( 'HA_RECAPTCHA_SITE_KEY', 'your-site-key' );
define( 'HA_RECAPTCHA_SECRET_KEY', 'your-secret-key' );

The site key is public, it is printed in the page. The secret key must stay on the server, so a constant in wp-config.php is better than an option in the database or a line in the theme.

The widget

<?php
add_action( 'wp_enqueue_scripts', function () {
    if ( is_page( 'contact' ) ) {
        wp_enqueue_script( 'google-recaptcha', 'https://www.google.com/recaptcha/api.js', array(), null, true );
    }
} );

In the form, which posts to admin-post.php:

<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
    <input type="hidden" name="action" value="ha_contact_form">
    <?php wp_nonce_field( 'ha_contact_form', 'ha_contact_nonce' ); ?>
    <!-- the form fields -->
    <div class="g-recaptcha" data-sitekey="<?php echo esc_attr( HA_RECAPTCHA_SITE_KEY ); ?>"></div>
    <button type="submit">Send</button>
</form>

The script finds the element and renders the checkbox in it. When the visitor passes the check, a hidden field g-recaptcha-response with a token is added to the form.

The check on the server

<?php
function ha_verify_recaptcha( $token ) {
    if ( '' === $token ) {
        return false;
    }

    $response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', array(
        'timeout' => 10,
        'body'    => array(
            'secret'   => HA_RECAPTCHA_SECRET_KEY,
            'response' => $token,
            'remoteip' => isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '',
        ),
    ) );

    if ( is_wp_error( $response ) ) {
        return false;
    }

    $body = json_decode( wp_remote_retrieve_body( $response ), true );

    return ! empty( $body['success'] );
}

add_action( 'admin_post_nopriv_ha_contact_form', 'ha_handle_contact_form' ); // guests
add_action( 'admin_post_ha_contact_form', 'ha_handle_contact_form' );        // logged-in users

function ha_handle_contact_form() {
    check_admin_referer( 'ha_contact_form', 'ha_contact_nonce' );

    $token = isset( $_POST['g-recaptcha-response'] ) ? sanitize_text_field( wp_unslash( $_POST['g-recaptcha-response'] ) ) : '';

    if ( ! ha_verify_recaptcha( $token ) ) {
        wp_die( esc_html__( 'Please confirm that you are not a robot.', 'textdomain' ), '', array( 'back_link' => true ) );
    }

    // validate the fields, send the mail...
    wp_safe_redirect( home_url( '/thank-you/' ) );
    exit;
}

A token can be verified only once and expires after two minutes, so verify it in the request that processes the form.

For Contact Form 7 none of this code is needed: it has its own reCAPTCHA integration under Contact → Integration, which since version 5.1 works with reCAPTCHA v3 (an invisible score instead of the checkbox).

NOTE: The server-side check is the part that protects the form. A bot does not load the widget at all, it posts the form fields directly, so a form that only shows the checkbox without verifying the token stops nobody.