雖然 WordPress 自帶了強大的垃圾留言過濾外掛 Akismet(點選這裡檢視 Akismet 終極攻略),但是隻能治標不治本,無法徹底遮蔽鋪天蓋地的垃圾資訊。所以,我們得出絕招,為你的主題新增算數驗證碼吧!
網上找了很多教程,不過步驟都很類似,總結大致方法如下:
第一步,把以下函式新增到主題的 functions.php 檔案中
function spam_protection_math(){
//獲取兩個隨機數, 範圍 5~15
$num1=rand(5,15);
$num2=rand(5,15);
//最終網頁中的具體內容
echo"<fieldset id='math'>"
."$num1 + $num2 = <input type='text' name='sum' id='sum' value='' tabindex='9'>"
."<input type='hidden' name='num1' value='$num1'>"
."<input type='hidden' name='num2' value='$num2'>"
."</fieldset>";
}
function spam_protection_pre($commentdata){
$sum=$_POST['sum'];//使用者提交的計算結果
switch($sum){
//得到正確的計算結果則直接跳出
case $_POST['num1']+$_POST['num2']:break;
//未填寫結果時的錯誤訊息
case null:wp_die('Error: please fill the math spam protection field.');break;
//計算錯誤時的錯誤訊息
default:wp_die('Error: in case of a wrong answer.');
}
return $commentdata;
}
if($comment_data['comment_type']==''){
add_filter('preprocess_comment','spam_protection_pre');
}
//獲取兩個隨機數, 範圍 5~15
$num1=rand(5,15);
$num2=rand(5,15);
//最終網頁中的具體內容
echo"<fieldset id='math'>"
."$num1 + $num2 = <input type='text' name='sum' id='sum' value='' tabindex='9'>"
."<input type='hidden' name='num1' value='$num1'>"
."<input type='hidden' name='num2' value='$num2'>"
."</fieldset>";
}
function spam_protection_pre($commentdata){
$sum=$_POST['sum'];//使用者提交的計算結果
switch($sum){
//得到正確的計算結果則直接跳出
case $_POST['num1']+$_POST['num2']:break;
//未填寫結果時的錯誤訊息
case null:wp_die('Error: please fill the math spam protection field.');break;
//計算錯誤時的錯誤訊息
default:wp_die('Error: in case of a wrong answer.');
}
return $commentdata;
}
if($comment_data['comment_type']==''){
add_filter('preprocess_comment','spam_protection_pre');
}
第二步,到評論檔案 comments.php 中新增如下程式碼:
<?php if(!is_user_logged_in())spam_protection_math();?>
最後定義一下 「row」 、 「math_textfield」 、 「small」 的 CSS 屬性即可。