有些時(shí)候,我們?yōu)榱嘶钴S下wordpress博客網(wǎng)站,會(huì)開啟文章底部的評(píng)論功能,讓看到這篇文章的人可以相互交流,但是,如果有一些評(píng)論的人惡意一點(diǎn),一直刷重復(fù)的評(píng)論,灌水咋辦?
- 代碼來(lái)源:詳情
這個(gè)時(shí)候,我們可以做個(gè)限制,讓一位評(píng)論用戶只能評(píng)論一次,如果重復(fù)提交的話,就返回一個(gè)提示,( 增加了對(duì)IP的判斷,更保險(xiǎn) )實(shí)現(xiàn)方法如下:
在主題的functions.php
文件的<?php
下添加以下代碼:
// 獲取評(píng)論用戶的ip,參考wp-includes/comment.php
function ludou_getIP() {
$ip = $_SERVER['REMOTE_ADDR'];
$ip = preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
return $ip;
}
function ludou_only_one_comment( $commentdata ) {
global $wpdb;
$currentUser = wp_get_current_user();
// 不限制管理員發(fā)表評(píng)論
if(empty($currentUser->roles) || !in_array('administrator', $currentUser->roles)) {
$bool = $wpdb->get_var("SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = ".$commentdata['comment_post_ID']." AND (comment_author = '".$commentdata['comment_author']."' OR comment_author_email = '".$commentdata['comment_author_email']."' OR comment_author_IP = '".ludou_getIP()."') LIMIT 0, 1;");
if($bool)
wp_die('本站每篇文章只允許評(píng)論一次。<a href="'.get_permalink($commentdata['comment_post_ID']).'">點(diǎn)此返回</a>');
}
return $commentdata;
}
add_action( 'preprocess_comment' , 'ludou_only_one_comment', 20);
測(cè)試效果如下
