reCaptcha sans plugin WordPress

Dans une politique de réduire les plugins WordPress, j'évoque ici une méthode efficace pour protéger tous les formulaires avec reCaptcha V2.

suivre :
plus
0
reCaptcha
reCaptcha

reCaptcha sans plugin WordPress

Edité le -

Un tutoriel pour vous aider a luter contre le spam.

Sommaire

Le temps de lecture pour cet article est d'environ 5 minutes

Toujours dans une politique stricte de réduire le nombre de plugins dans WordPress, je présente ici une méthode simple et efficace pour protéger la totalité des formulaires contre le spam avec reCaptcha V2:
  • Le formulaire des commentaires
  • Le formulaire d’accès à l’administration (wp-login)
  • Le formulaire d’inscription (wp-register)
  • Et enfin le formulaire du mot de passe perdu

Obtenir les clés pour reCaptcha V2 via les services Google

Pour ce faire, suivez les instructions sur les services Google. Cherchez a obtenir la V2, case à cocher. Je la préfère à la V3 qui émet un petit logo en bas a droite du site, ce n’est pas très explicite.
inscription recaptacha v2
Inscription reCaptacha v2
Vous obtenez après validation, les fameuses clés à renseigner dans notre code PHP.
Clés reCaptcha V2
Après avoir obtenu vos clés publique et secrète, nous allons éditer le fichier functions.php de votre thème. On ne le répète pas assez souvent, faites un thème enfant de préférence afin que les mises à jour de votre thème n’écrasent pas vos modifications.
function my_recaptcha_key(){
	$sitekey= "00000000000000000000000000000";
	$secretkey= "00000000000000000000000000000";
	return explode(",", $sitekey.",".$secretkey ); 	
}
Bien évidement, vous indiquez vos clés, cela va de soi…

reCaptcha sans plugin pour les commentaires WordPress

Pour afficher la case a cocher afin de protéger vos commentaires sur WordPress, toujours dans functions.php
/*
*Add reCAPTCHA to WordPress Comment Section
*/
add_action( 'wp_head', function(){
wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js');
} );
function add_google_recaptcha($submit_field) {
    $submit_field['submit_field'] = '<div class="g-recaptcha" data-sitekey="'.my_recaptcha_key()[0].'"></div><br>' . $submit_field['submit_field'];
    return $submit_field;
}
if (!is_user_logged_in()) {
    add_filter('comment_form_defaults','add_google_recaptcha');
}
function is_valid_captcha($captcha) {
$captcha_postdata = http_build_query(array(
                            'secret' => my_recaptcha_key()[1],
                            'response' => $captcha,
                            'remoteip' => $_SERVER['REMOTE_ADDR']));
$captcha_opts = array('http' => array(
                      'method'  => 'POST',
                      'header'  => 'Content-type: application/x-www-form-urlencoded',
                      'content' => $captcha_postdata));
$captcha_context  = stream_context_create($captcha_opts);
$captcha_response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify" , false , $captcha_context), true);
if ($captcha_response['success'])
    return true;
else
    return false;
}
 
function verify_google_recaptcha() {
$recaptcha = $_POST['g-recaptcha-response'];
if (empty($recaptcha))
    wp_die( __("<b>ERROR:</b> please select <b>I'm not a robot!</b><p><a href='javascript:history.back()'>« Back</a></p>"));
else if (!is_valid_captcha($recaptcha))
    wp_die( __("<b>Go away SPAMMER!</b>"));
}
if (!is_user_logged_in()) {
    add_action('pre_comment_on_post', 'verify_google_recaptcha');
}

reCaptcha pour le login l’espace d’administration WordPress

Pour afficher la case a cocher afin de vous prémunir d’essai frauduleux sur le login admin de WordPress, continuez avec ce code dans functions.php
/*
*Add reCaptcha on WordPress Admin Login Page Without Plugin
*/

function login_style() {
    wp_register_script('login-recaptcha', 'https://www.google.com/recaptcha/api.js', false, NULL);
    wp_enqueue_script('login-recaptcha');
	echo "<style>p.submit, p.forgetmenot {margin-top: 10px!important;}.login form{width: 303px;} div#login_error {width: 322px;}</style>";
}
add_action('login_enqueue_scripts', 'login_style');
function add_recaptcha_on_login_page() {
    echo '<div class="g-recaptcha brochure__form__captcha" data-sitekey="'.my_recaptcha_key()[0].'"></div>';
}
add_action('login_form','add_recaptcha_on_login_page');
function captcha_login_check($user, $password) {
    if (!empty($_POST['g-recaptcha-response'])) {
        $secret = my_recaptcha_key()[1];
        $ip = $_SERVER['REMOTE_ADDR'];
        $captcha = $_POST['g-recaptcha-response'];
        $rsp = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $captcha .'&remoteip='. $ip);
        $valid = json_decode($rsp, true);
        if ($valid["success"] == true) {
            return $user;
        } else {
            return new WP_Error('Captcha Invalid', __('<center>Captcha Invalid! Please check the captcha!</center>'));
        }
    } else {
        return new WP_Error('Captcha Invalid', __('<center>Captcha Invalid! Please check the captcha!</center>'));
    }
}
add_action('wp_authenticate_user', 'captcha_login_check', 10, 2);

reCaptcha pour le formulaire de perte du mot de passe WordPress

Pour afficher la case a cocher sur le formulaire WordPress concernant la perte du mot de passe, vous continuez avec ce code dans functions.php
/*
*Add reCaptcha to Lost Password Form Without Plugin
*/
function recaptcha() {
    echo '<script src="https://www.google.com/recaptcha/api.js" async defer></script>';
    echo '<div class="g-recaptcha brochure__form__captcha" data-sitekey="'.my_recaptcha_key()[0].'"></div>';
	echo '<style>p.message {width: 324px;}</style>';
}
add_action('lostpassword_form', 'recaptcha');

function captcha_lostpassword_check($errors) {
    if (!empty($_POST['g-recaptcha-response'])) {
        $secret = my_recaptcha_key()[1];
        $ip = $_SERVER['REMOTE_ADDR'];
        $captcha = $_POST['g-recaptcha-response'];
        $rsp = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $captcha .'&remoteip='. $ip);
        $valid = json_decode($rsp, true);
        if ($valid["success"] == true) {
           
        } else {
            $errors->add('Captcha Invalid', __('Captcha Invalid! Please check the captcha!'));
        }
    } else {
        $errors->add('Captcha Invalid', __('Captcha Invalid! Please check the captcha!'));
    }
}
add_action( 'lostpassword_post', 'captcha_lostpassword_check', 10, 1 );

reCaptcha pour le formulaire d’inscription sans plugin WordPress

Et enfin, pour afficher la case a cocher reCaptcha sur le formulaire d’inscription de WordPress, toujours dans functions.php
/*
*Protect WordPress Site Registration Form with reCaptcha
*/
function recaptcha_register_form() {
    echo '<script src="https://www.google.com/recaptcha/api.js" async defer></script>';
    echo '<div class="g-recaptcha brochure__form__captcha" data-sitekey="'.my_recaptcha_key()[0].'"></div>';
	echo'<style>p.message.register {
    width: 324px;
}</style>';
}
add_action('register_form', 'recaptcha_register_form');

function captcha_registration_check($errors, $user_login, $user_email) {
    if (!empty($_POST['g-recaptcha-response'])) {
        $secret = my_recaptcha_key()[1];
        $ip = $_SERVER['REMOTE_ADDR'];
        $captcha = $_POST['g-recaptcha-response'];
        $rsp = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $captcha .'&remoteip='. $ip);
        $valid = json_decode($rsp, true);
        if ($valid["success"] == true) {
            return $errors;
        } else {
            return new WP_Error('Captcha Invalid', __('Captcha Invalid! Please check the captcha!'));
        }
    } else {
        return new WP_Error('Captcha Invalid', __('Captcha Invalid! Please check the captcha!'));
    }
}
add_action('registration_errors', 'captcha_registration_check', 10, 3);
N’hésitez pas a poser des questions en commentaire, normalement, ce n’est que du copier / coller.

Publié dans WordPress

Tagué , ,