有些時候,我們為了活躍下wordpress博客網站,會開啟文章底部的評論功能,讓看到這篇文章的人可以相互交流,但是,如果有一些評論的人惡意一點,一直刷重復的評論,灌水咋辦?
- 代碼來源:詳情
這個時候,我們可以做個限制,讓一位評論用戶只能評論一次,如果重復提交的話,就返回一個提示,( 增加了對IP的判斷,更保險 )實現方法如下:
在主題的functions.php
文件的<?php
下添加以下代碼:
// 獲取評論用戶的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();
// 不限制管理員發表評論
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('本站每篇文章只允許評論一次。<a href="'.get_permalink($commentdata['comment_post_ID']).'">點此返回</a>');
}
return $commentdata;
}
add_action( 'preprocess_comment' , 'ludou_only_one_comment', 20);
測試效果如下
