Skip to content

Instantly share code, notes, and snippets.

@BaskSerg
Last active March 27, 2020 17:17
Show Gist options
  • Save BaskSerg/6d5840b12435795c63dc7e05371375cb to your computer and use it in GitHub Desktop.
Save BaskSerg/6d5840b12435795c63dc7e05371375cb to your computer and use it in GitHub Desktop.
Add ReCaptcha to comments Wordpress
<?php
// Add to functions.php
add_action( 'wp_enqueue_scripts', 'add_recaptcha_js', 5, 1 );
function add_recaptcha_js() {
// Registration reCAPTHCA api.js, version - null, in footer - false
wp_register_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js?hl=en', array(), null, false );
// Include reCAPTHCA api.js
wp_enqueue_script( 'recaptcha' );
}
add_filter('comment_form_submit_button', 'filter_comment_form_submit_button', 10, 2);
function filter_comment_form_submit_button($submit_button) {
/* ReCaptcha only for anonymous users
global $user_ID;
if (!$user_ID){
$recaptcha_site_key = 'Site Key';
echo '<div class="g-recaptcha" data-sitekey="'.$recaptcha_site_key.'"></div>';
}
*/
/* For all users */
$recaptcha_site_key = 'Site key';
echo '<div class="g-recaptcha" data-sitekey="'.$recaptcha_site_key.'"></div>';
$submit_before = '<div class="form-group">';
$submit_after = '</div>';
return $submit_before . $submit_button . $submit_after;
}
function verify_recaptcha_response() {
$recaptcha_secret_key = 'Secret Key';
$recaptcha_site_key = 'Site Key';
if ( isset ( $_POST['g-recaptcha-response'] ) ) {
$captcha_response = $_POST['g-recaptcha-response'];
} else {
return false;
}
// Verify the captcha response from Google
$response = wp_remote_post(
'https://www.google.com/recaptcha/api/siteverify',
array(
'body' => array(
'secret' => $recaptcha_secret_key,
'response' => $captcha_response
)
)
);
$success = false;
if ( $response && is_array( $response ) ) {
$decoded_response = json_decode( $response['body'] );
$success = $decoded_response->success;
}
return $success;
}
add_action('preprocess_comment', "preprocess_comment_cb");
function preprocess_comment_cb($commentdata) {
/* ReCaptcha only for anonymous users
global $user_ID;
if ($user_ID) {
return $commentdata;
}
*/
if ( ! verify_recaptcha_response() ) {
echo '<p style="font-size: 1rem;">You are not verified reCaptcha test. Return to the <a href="#" onclick="history.go(-1);">previous page </a> and try again.';
exit;
}
return $commentdata;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment