最后更新时间为 2019年10月30日
简单两种验证方式,都是从网上搬运来的。
随机数字加法运算验证:
截图:
代码: (放在你当前主题的functions函数文件里即可)
//WordPress新用户注册随机数学验证码
function add_security_question_fields() {
//获取两个随机数, 范围0~9
$num1=rand(1,9);
$num2=rand(2,9);
//最终网页中的具体内容
echo "<p><label for='math' class='small'>验证码:$num1 + $num2 = ? </label><input type='text' name='sum' class='input' value='' size='25'>"
."<input type='hidden' name='num1' value='$num1'>"
."<input type='hidden' name='num2' value='$num2'></p>";}
add_action('register_form','add_security_question_fields');
add_action( 'register_post', 'add_security_question_validate', 10, 3 );
function add_security_question_validate( $sanitized_user_login, $user_email, $errors) {
$sum=$_POST['sum'];//用户提交的计算结果
switch($sum){
//得到正确的计算结果则直接跳出
case $_POST['num1']+$_POST['num2']:break;
//未填写结果时的错误讯息
case null:wp_die('错误:请输入验证码!');break;
//计算错误时的错误讯息
default:wp_die('错误:验证码错误,请重试!');}}
add_action( 'add_security_question','register_form' );
自定义问题答案验证
截图:
代码: (放在你当前主题的functions函数文件里即可)
/*注册验证*/
function rand_reg_question(){
$register_number=rand(0,1); // 设置随机数的返回范围
$_SESSION['register_number']=$register_number;
}
add_action('login_head','rand_reg_question');
global $register_questions;
global $register_answers;
// 添加问题数组
$register_questions=array('中国首都在哪里?','1+1+1等于多少?');
// 添加答案数组(与上面的问题对应)
$register_answers=array('北京','3');
add_action( 'register_form', 'add_security_question' );
function add_security_question() {
global $register_questions;
$register_number=$_SESSION['register_number'];
?>
<p>
<label><?php echo $register_questions[$register_number];?><br />
<input type="text" name="user_proof" id="user_proof" class="input" size="25" tabindex="20" />
</label>
</p>
<?php }
add_action( 'register_post', 'add_security_question_validate', 10, 3 );
function add_security_question_validate( $sanitized_user_login, $user_email, $errors) {
global $register_answers;
$register_number=$_SESSION['register_number'];
if (!isset($_POST[ 'user_proof' ]) || empty($_POST[ 'user_proof' ])) {
return $errors->add( 'proofempty', '<strong>错误</strong>: 您还没有回答问题。' );
} elseif ( strtolower( $_POST[ 'user_proof' ] ) != $register_answers[$register_number] ) {
return $errors->add( 'prooffail', '<strong>错误</strong>: 您的回答不正确。' );
}
}