在設(shè)定的時(shí)間內(nèi),除了對(duì)當(dāng)前文章生效,對(duì)其他文章同樣生效,需過(guò)了設(shè)定時(shí)間才可繼續(xù)評(píng)論
各種垃圾評(píng)論讓我們防不勝防,但我們可以通過(guò)合理的設(shè)計(jì)各種限制,在一定情況下緩解。這一次分享的就是限制用戶評(píng)論太快的代碼。

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