首页 问答 正文

如何在WordPress中添加登录验证码

注册会员 / 悠然自学 / 2023-06-11/ 浏览 120 次

在WordPress中添加登录验证码,可以使用插件或者手动添加代码实现。

  1. 使用插件

在WordPress插件库中搜索“Google Captcha (reCAPTCHA) by BestWebSoft”,安装并启用插件。在设置中选择登录表单并选择reCAPTCHA类型(v2或v3),输入网站的网址和密钥,保存设置即可。

  1. 手动添加代码

在当前主题的functions.php文件中添加以下代码:

function add_login_captcha() {
    if ( !is_user_logged_in() ) {
        wp_enqueue_script( 'google-captcha', 'https://www.google.com/recaptcha/api.js' );
    }
}
add_action( 'login_enqueue_scripts', 'add_login_captcha' );

function verify_login_captcha() {
    if ( isset( $_POST['log'] ) && isset( $_POST['pwd'] ) ) {
        if ( !isset( $_POST['g-recaptcha-response'] ) || empty( $_POST['g-recaptcha-response'] ) ) {
            wp_die( '请完成验证码以登录。' );
        } else {
            $secret = 'your_secret_key';
            $remoteip = $_SERVER['REMOTE_ADDR'];
            $response = $_POST['g-recaptcha-response'];
            $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip";
            $json = file_get_contents( $url );
            $captcha = json_decode( $json );
            if ( !$captcha->success ) {
                wp_die( '验证码错误,请重新输入。' );
            }
        }
    }
}
add_action( 'wp_authenticate', 'verify_login_captcha' ); 

需要将代码中的“your_secret_key”替换成在Google reCAPTCHA创建的密钥。同时,需要在登录页面的表单中添加以下代码:

<div class="g-recaptcha" data-sitekey="your_site_key"></div> 

同样,需要将代码中的“your_site_key”替换成在Google reCAPTCHA创建的网站密钥。

大家谈论
    我的见解