为 WordPress 网站添加登录验证码,主要有插件安装(新手推荐)和代码手动实现(进阶)两种方式。以下是最常用、最稳定的两种方案:
一、插件方案(最简单、最安全)
推荐使用 Login Security Captcha 插件,支持 Google reCAPTCHA、Cloudflare Turnstile 等多种验证方式WordPress.org。
步骤 1:安装并激活
- 进入 WordPress 后台 → 插件 → 安装插件
- 搜索:
Login Security Captcha - 安装并启用
步骤 2:设置验证码(以 reCAPTCHA v2 为例)
- 进入:设置 → Login Security Captcha
- 选择 reCAPTCHA Version →
reCAPTCHA v2 - 去 Google reCAPTCHA 官网 注册获取:
Site KeySecret Key
- 把两个密钥填入插件设置
- 在 Enable Captcha For 里勾选:
- Login Form(登录页)
- 可选:Registration、Reset Password 等
- 保存设置 → 刷新登录页,验证码已生效WordPress.org。
二、代码手动添加(数学验证码,无插件)
适合不想装插件、会改代码的用户。直接在当前主题的 functions.php 添加以下代码。
// 登录页添加数学验证码
function add_math_captcha_to_login() {
$num1 = rand(1, 9);
$num2 = rand(1, 9);
echo '
<p class="login-captcha">
<label for="math_captcha">验证码:' . $num1 . ' + ' . $num2 . ' = ?</label>
<input type="text" name="math_captcha" id="math_captcha" class="input" size="20" style="margin-top:5px;" required>
<input type="hidden" name="num1" value="' . $num1 . '">
<input type="hidden" name="num2" value="' . $num2 . '">
</p>';
}
add_action('login_form', 'add_math_captcha_to_login');
// 验证验证码
function validate_math_captcha_on_login($user, $password) {
if (isset($_POST['math_captcha'])) {
$sum = (int)$_POST['math_captcha'];
$num1 = (int)$_POST['num1'];
$num2 = (int)$_POST['num2'];
if ($sum !== $num1 + $num2) {
return new WP_Error('captcha_error', '❌ 验证码错误,请重新计算。');
}
} else {
return new WP_Error('captcha_error', '❌ 请输入验证码。');
}
return $user;
}
add_filter('wp_authenticate_user', 'validate_math_captcha_on_login', 10, 2);
感谢您的支持!
微信
支付宝
关闭
👁 阅读量:20 次
