Integrating Google reCAPTCHA v3 into your WordPress site involves adding frontend and backend checks. Here’s how to do it step-by-step for the wp-login.php and wp-admin registration pages:
- Get Your reCAPTCHA v3 Keys:
- Go to the reCAPTCHA website.
- Register your site for reCAPTCHA v3.
- Obtain the SITE KEY and SECRET KEY.
- Integrate reCAPTCHA v3 in WordPress:
- Enqueue reCAPTCHA v3 script on login and registration page:
- Add the following to your theme’s functions.php:
- Replace `YOUR_SITE_KEY` with your actual site key.
- Enqueue reCAPTCHA v3 script on login and registration page:
function enqueue_recaptcha_script() {
if ( in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) {
echo '<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute("YOUR_SITE_KEY", {action: "login"}).then(function(token) {
var recaptchaInput = document.createElement("input");
recaptchaInput.type = "hidden";
recaptchaInput.value = token;
recaptchaInput.name = "g-recaptcha-response";
document.getElementById("loginform").appendChild(recaptchaInput);
});
});
</script>';
}
}
add_action( 'login_enqueue_scripts', 'enqueue_recaptcha_script' );
-
- Verify reCAPTCHA response on server side:
- Add the following code to your functions.php:
- Verify reCAPTCHA response on server side:
function verify_recaptcha_response() {
if ( isset( $_POST['g-recaptcha-response'] ) && $_POST['g-recaptcha-response'] ) {
$recaptcha_secret = 'YOUR_SECRET_KEY';
$response = wp_remote_get( "https://www.google.com/recaptcha/api/siteverify?secret=$recaptcha_secret&response=" . $_POST['g-recaptcha-response'] );
$response_keys = json_decode( $response['body'], true );
if ( intval( $response_keys["success"] ) !== 1 ) {
wp_die( 'Google reCAPTCHA verification failed. Please try again.' );
} elseif ( $response_keys['action'] != 'login' || $response_keys['score'] < 0.5 ) {
wp_die( 'Sorry, your action looks suspicious and has been blocked.' );
}
} else {
wp_die( 'Google reCAPTCHA token is missing. Please try again.' );
}
}
add_action( 'login_form_login', 'verify_recaptcha_response' );
add_action( 'login_form_register', 'verify_recaptcha_response' );
-
-
- Replace YOUR_SECRET_KEY with your actual secret key.
-
3. Test: Now, when you try to log in or register from the wp-login.php page, you’ll have to pass the reCAPTCHA v3 test.
Note: The above code only integrates reCAPTCHA v3 with the default WordPress login and registration form. If you’re using a custom login or registration form, you may need to adjust the code accordingly.
Note: Always take a backup of your site before making such changes and possibly test on a staging environment first.