Google reCAPTCHA v2 (“I’m not a robot” checkbox) protects contact forms, registration forms, and comment sections from spam bots. Adding it to a WordPress form takes a site key, a secret key, and two steps: render the widget on the front end and verify the token on the server.
Problem: A WordPress contact form or user registration page is receiving spam submissions that pass through basic honeypot checks.
Solution: Add Google reCAPTCHA v2 — register site and secret keys in the Google console, enqueue the reCAPTCHA script, add the g-recaptcha widget to the form, and verify the response token server-side with a wp_remote_post() call to the reCAPTCHA API before processing the submission.
Register for free at google.com/recaptcha, choose reCAPTCHA v2, and get your site key and secret key. Then enqueue the reCAPTCHA script and render the widget:
define( 'RECAPTCHA_SITE_KEY', 'YOUR_SITE_KEY' );
define( 'RECAPTCHA_SECRET_KEY', 'YOUR_SECRET_KEY' );
// Enqueue the reCAPTCHA library
add_action( 'wp_enqueue_scripts', function() {
if ( is_page( 'contact' ) ) {
wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js', [], null, true );
}
} );
// Render the widget inside your form (output in a template or shortcode)
function render_recaptcha_widget() {
echo '<div class="g-recaptcha" data-sitekey="' . esc_attr( RECAPTCHA_SITE_KEY ) . '"></div>';
}
Verify the token server-side when the form is submitted:
function verify_recaptcha( $token ) {
if ( empty( $token ) ) {
return false;
}
$response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', [
'body' => [
'secret' => RECAPTCHA_SECRET_KEY,
'response' => sanitize_text_field( $token ),
'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
],
] );
if ( is_wp_error( $response ) ) {
return false;
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
return ! empty( $body['success'] );
}
// In your form handler:
add_action( 'admin_post_nopriv_submit_contact_form', 'handle_contact_form' );
function handle_contact_form() {
$token = isset( $_POST['g-recaptcha-response'] ) ? $_POST['g-recaptcha-response'] : '';
if ( ! verify_recaptcha( $token ) ) {
wp_die( 'reCAPTCHA verification failed. Please try again.' );
}
// Process the form...
}
NOTE: Never skip the server-side verification step. A bot can submit the form without the reCAPTCHA widget ever loading in a browser — the only trustworthy check is validating the token with Google's API from your server. Store your secret key in wp-config.php as a constant rather than in an option in the database.