Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add reCAPTCHA to WooCommerce Signup Form
<?php
/* wooc_reCAPTCHA */
// Add reCAPTCHA to WooCommerce Signup Form
function wooc_reCAPTCHA(){
?>
<script src='https://www.google.com/recaptcha/api.js' defer'></script>
<label>ARE YOU HUMAN?</label>
<div class="g-recaptcha" data-sitekey="[reCAPTCHA Site Key]"></div>
<?php
}
add_action( 'woocommerce_register_form', 'wooc_reCAPTCHA', 19);
// Validate reCAPTCHA input before creating account
function wooc_validate_re_captcha_field( $username, $email, $wpErrors ){
$remoteIP = $_SERVER['REMOTE_ADDR'];
$recaptchaResponse = $_POST['g-recaptcha-response'];
$response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', [
'body' => [
'secret' => '[reCAPTCHA Secret Key]',
'response' => $recaptchaResponse,
'remoteip' => $remoteIP
]
] );
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = wp_remote_retrieve_body( $response );
if ( $response_code == 200 ){
$result = json_decode( $response_body, true );
if ( ! $result['success'] ){
switch ( $result['error-codes'] ){
case 'missing-input-secret':
case 'invalid-input-secret':
$wpErrors->add( 'recaptcha', __( 'Invalid reCAPTCHA secret key.', 'woocommerce' ) );
break;
case 'missing-input-response' :
case 'invalid-input-response' :
$wpErrors->add( 'recaptcha', __( 'Please check the box to prove that you are not a robot.', 'woocommerce' ) );
break;
default:
$wpErrors->add( 'recaptcha', __( 'Something went wrong validating the reCAPTCHA.', 'woocommerce' ) );
break;
}
}
}
else {
$wpErrors->add( 'recaptcha_error', __( 'Unable to reach the reCAPTCHA server.', 'woocommerce' ) );
}
}
add_action( 'woocommerce_register_post', 'wooc_validate_re_captcha_field', 9, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.