WordPress 评论添加验证码

垃圾评论是无法避免的,一般可以开启评论审核不让垃圾评论第一时间显示,但这并不能阻断垃圾评论的产生。所以我们需要验证码防止机器人评论广告信息,不用安装任何插件就能现实验证码功能。

将代码添加到当前主题的 functions.php 中:

一:数字加法两个随机数验证码

function loper_protection_math(){
# 数字加法两个随机数, 范围0~99
$num1=rand(0,9);
$num2=rand(0,9);
echo "<input type=\"text\" name=\"sum\" class=\"text\" value=\"\" size=\"25\" tabindex=\"4\" placeholder=\"$num1 + $num2 = ?\" >\n";
echo "<input type=\"hidden\" name=\"num1\" value=\"$num1\">\n";
echo "<input type=\"hidden\" name=\"num2\" value=\"$num2\">";
echo "<label for=\"math\">请输入(计算结果)</label>\n";
}
function loper_protection_pre($commentdata){
$sum=$_POST['sum'];
switch($sum){
case $_POST['num1']+$_POST['num2']:
break;case null:err('错误: 请输入验证码。');
break;default:err('错误: 验证码错误。');}
return $commentdata;}
if($comment_data['comment_type']==''){
add_filter('preprocess_comment','loper_protection_pre');}

二:英文数字随机数验证码

function loper_protection_math(){
$num1=substr(md5(mt_rand(0,99)),0,5);
# 英文数字随机数, 范围0~99
echo "<input type=\"text\" name=\"sum\" class=\"text\" value=\"\" size=\"25\" tabindex=\"4\">\n";
echo "<input type=\"hidden\" name=\"num1\" value=\"$num1\">\n";
echo "<label for=\"math\" >请输入( $num1 )</label>\n";
}
function loper_protection_pre($commentdata){
$sum=$_POST['sum'];
switch($sum){
case $_POST['num1']:
break;case null:err('错误: 请输入验证码。');
break;default:err('错误: 验证码错误。');}
return $commentdata;}
if($comment_data['comment_type']==''){
add_filter('preprocess_comment','loper_protection_pre');}

调用代码:

<?php loper_protection_math();?>
(1)

相关推荐