Wordpress评论添加数学验证码,防止垃圾评论。

Function代码

//数学加法验证码,by minirizhi.com
add_action('comment_form_after_fields', 'spam_protection_math', 1, 1);
function spam_protection_math(){
//获取两个随机数, 范围0~9
$num1=rand(0,9);
$num2=rand(0,9);
//最终网页中的具体内容
echo "<div class='comment-form-url form-group has-feedback'><div class='input-group'><div class='input-group-addon'><i class='fa fa-check'></i></div><input type='text' name='sum' aria-required='true' required class='form-control' value='' size='25' tabindex='4' placeholder='$num1 + $num2 = ?'><span class='form-control-feedback required'>*</span></div></div>"
."<input type='hidden' name='num1' value='$num1'>"
."<input type='hidden' name='num2' value='$num2'>";
}
function spam_protection_pre($commentdata){
$sum=$_POST['sum'];//用户提交的计算结果
switch($sum){
//得到正确的计算结果则直接跳出
case $_POST['num1']+$_POST['num2']:break;
//未填写结果时的错误讯息
case null:wp_die('<p align="center">没有输入验证码! <a href="javascript:history.back(-1)">点击返回</a></p>');break;
//计算错误时的错误讯息
default:wp_die('<p align="center">验证码错误! <a href="javascript:history.back(-1)">点击返回</a></p>');
}
return $commentdata;
}
if($comment_data['comment_type']==''){
add_filter('pre_comment_on_post','spam_protection_pre');
}
文章目录