To add a reCAPTCHA, you’ll need to register your site at https://www.google.com/recaptcha, and obtain a SITE_KEY and a SECRET_KEY. You can then add the following code blocks to your theme functions.php
file to setup the reCAPTCHA field on the Wishlist form.
Add the reCAPTCHA field to the Wishlist submission fields.
function add_recaptcha_field( $fields ) {
$fields['recaptcha'] = [
'type' => 'custom',
'label' => 'Recaptcha',
'callback' => 'render_recaptcha_field',
];
return $fields;
}
add_filter( 'rw_elephant_wishlist_form_fields', 'add_recaptcha_field' );
Enqueue reCAPTCHA api script on the Wishlist submission page.
function enqueue_wishlist_recaptcha() {
if ( ! is_rwe_wishlist_submission_page() ) {
return;
}
wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_wishlist_recaptcha' );
Render the reCAPTCHA on the Wishlist submission form (after the other form fields, and before the Submit button).
// Remember to replace "RECAPTCHA_SITE_KEY" with your own reCAPTCHA Site Key
function render_recaptcha_field() {
print( '<div class="g-recaptcha" data-callback="testing" data-sitekey="RECAPTCHA_SITE_KEY"></div>' );
}
Include the new reCAPTCHA form field when validating the Wishlist form on Submit.
// Remember to replace "RECAPTCHA_SECRET_KEY" with your own reCAPTCHA Secret Key
function validate_recaptcha( $wishlist_api, $query_args, $form_fields ) {
$url = add_query_arg(
[
'secret' => 'RECAPTCHA_SECRET_KEY',
'response' => isset( $form_fields['g-recaptcha-response'] ) ? $form_fields['g-recaptcha-response'] : '',
'remoteip' => isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'],
],
'https://www.google.com/recaptcha/api/siteverify'
);
$response = wp_remote_get( $url );
if ( is_wp_error( $response ) ) {
$wishlist_api->add_error( $response->get_error_message() );
return;
}
$body = json_decode( $response['body'], true );
if ( ! empty( $body ) && $body['success'] ) {
return;
}
$wishlist_api->add_error( 'The reCaptcha response does not appear valid. Please try again.' );
}
add_action( 'rw_elephant_submit_wishlist', 'validate_recaptcha', 10, 3 );
You should now see the reCAPTCHA appear just before the Wishlist Submit button within the form. When a user submits the Wishlist form they will now be required to tick the checkbox to confirm that they are a genuine user.
You can currently see an example of the working reCAPTCHA by submitting a test Wishlist though the Musical Chairs website.