Skip to content

Instantly share code, notes, and snippets.

@mitchellkrogza
Forked from joshcanhelp/google-recaptcha.php
Created December 6, 2023 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchellkrogza/e6a312cde0b6c93e85a4acb88a70865c to your computer and use it in GitHub Desktop.
Save mitchellkrogza/e6a312cde0b6c93e85a4acb88a70865c to your computer and use it in GitHub Desktop.
Add a Google RECAPTCHA and honeypot to a WordPress registration form
<?php
/**
* Adds first and last name to the registration field
*/
function proper_add_user_reg_fields () {
?>
<p class="reg-email-validation">
<label for="confirm_email_address">
<?php _e( 'Confirm email address', 'properwp' ) ?><br>
<input type="text" name="confirm_email_address" id="confirm_email_address" class="input" value="">
</label>
</p>
<div class="g-recaptcha" data-sitekey="[[GOOGE SITEKEY]]"></div>
<script src='https://www.google.com/recaptcha/api.js'></script>
<?php
}
add_action( 'register_form', 'proper_add_user_reg_fields', 20 );
/**
* Require first and last name
*
* @param $errors
*
* @return mixed
*/
function proper_add_user_reg_fields_validation ( $errors ) {
// Check for honeypot
if ( ! empty( $_POST['confirm_email_address'] ) ) {
$errors->add( 'honeypot_error', '<strong>ERROR</strong>: Security check failed [1]' );
}
// Recaptcha check
if ( isset( $_POST['wp-submit'] ) && empty( $_POST['g-recaptcha-response'] ) ) {
$errors->add( 'recpatcha_error', '<strong>ERROR</strong>: Please verify that you are not a robot.' );
} else if ( isset( $_POST['wp-submit'] ) ) {
$response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', array(
'body' => array(
'secret' => '[[GOOGLE RECAPTCHA API KEY]]',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
) );
$response_body = json_decode( $response['body'] );
if ( empty( $response_body->success ) || ! $response_body->success ) {
$errors->add( 'recpatcha_error', '<strong>ERROR</strong>: Security check failed [3]' );
}
}
return $errors;
}
add_filter( 'registration_errors', 'proper_add_user_reg_fields_validation', 20 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment