WordPress添加评论验证码功能

WordPress没有为评论开发验证码功能,尤其遇上机器人的垃圾评论,实在是防不胜防,因此添加验证码功能才是最终解决问题的方法。

编写代码

有两种方案实现评论验证,一种是计算两个随机数之各,另一种是输入随机英文或数字。在主题的functions.php中加入以下代码:

方案一 计算10以内的加法

//评论:计算10以内的加法
function comments_verification(){
  $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 comments_verification_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','comments_verification_pre');
}

方案二 随机英文和数字

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

实现方法

在主题的comments.php中的合适位置加入以下代码:

<?php comments_verification();?>

原创文章禁止转载:技术学堂 » WordPress添加评论验证码功能

精彩评论

7+9=

感谢您的支持与鼓励

支付宝扫一扫打赏

微信扫一扫打赏