Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Created July 12, 2021 06:21
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 finalwebsites/fd387213e4819b4391e14a93f3cc4298 to your computer and use it in GitHub Desktop.
Save finalwebsites/fd387213e4819b4391e14a93f3cc4298 to your computer and use it in GitHub Desktop.
reCaptacha for HTML Forms
<?php
function fws_enqueue_recaptcha() {
$sitekey = mysitekey';
wp_enqueue_script( 'fws-recaptcha', '//www.google.com/recaptcha/api.js?render=' . $sitekey, null, null, true );
}
add_action( 'wp_enqueue_scripts', 'oceanwp_child_enqueue_parent_style' );
add_filter( 'hf_validate_form', function( $error_code, $form, $data ) {
$valid_captcha = '';
if (isset($_POST['recaptcha_response'])) {
$recaptcha_response = sanitize_text_field($_POST['recaptcha_response']);
$secret = 'mysecretkey';
$request = wp_remote_get('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $recaptcha_response);
$request_body = wp_remote_retrieve_body( $request );
$recaptcha = json_decode($request_body);
//var_dump($recaptcha);
if ($recaptcha->score < 0.5) {
$valid_captcha = 'invalid_captcha';
}
} else {
$valid_captcha = 'invalid_captcha';
}
return $error_code;
}, 10, 3 );
add_filter( 'hf_form_message_invalid_captcha', function( $message ) {
return 'Sorry, your message isn\'t valid, pleease try again';
});
// this isn't working
jQuery(document).ready(function($) {
$('#contactbutton').on('click', function (event) {
event.preventDefault();
grecaptcha.ready(function () {
grecaptcha.execute(ajax_object_acf.site_key, { action: 'contactform_action' }).then(function (token) {
// submit the form
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment