各種垃圾評論讓我們防不勝防,但我們可以通過合理的設計各種限制,在一定情況下緩解。這一次分享的就是限制用戶評論太快的代碼。

在設定的時間內,除了對當前文章生效,對其他文章同樣生效,需過了設定時間才可繼續(xù)評論。
在主題根目錄下的functions.php
文件中的<?php
下添加以下代碼并保存。
//評論間隔
add_filter('comment_flood_filter', 'suren_comment_flood_filter', 10, 3);
function suren_comment_flood_filter($flood_control, $time_last, $time_new)
{
$seconds = 60;//間隔時間
if(($time_new - $time_last) < $seconds)
{
$time=$seconds-($time_new - $time_last);
wp_die ('評論過快!請'. $time.'秒后再次評論');
}
else
{
return false;
}
}
實戰(zhàn)優(yōu)化
- 在實戰(zhàn)中,需要將函數內的信息抽離到外部,方便維護,
- 貼合實際體驗,添加了返回按鈕,避免用戶誤操作
add_filter('comment_flood_filter', array(__CLASS__, 'suren_comment_flood_filter'), 10, 3);
/**
* 效果:兩次評論之間間隔
* 來源:http://www.kartiktrivedi.com/19960.html
*/
public static function suren_comment_flood_filter($flood_control, $time_last, $time_new)
{
$interval_time = 5;
$seconds = $interval_time; //間隔時間
if (($time_new - $time_last) < $seconds) {
$time = $seconds - ($time_new - $time_last);
$message = '評論過快!請' . $time . '秒后再來評論';
$message .= '<br/><a href="#" onclick="history.back();">
<button class="button" style="margin: 1em 0;">返回</button>
</a>';
wp_die($message);
} else {
return false;
}
}