之前有網(wǎng)友提出,,在WordPress中有沒有辦法實現(xiàn)每篇文章只允許用戶評論一次,?
暫不說這個需求有沒有用,畢竟WordPress就是給有各種需求的人用的,。這個功能實現(xiàn)起來也比較簡單,,只需每次用戶發(fā)表的評論進數(shù)據(jù)庫之前,從當前文章的所有評論中查找是否有相同的用戶名或郵箱已經(jīng)發(fā)表過評論,,如果有就跳到錯誤頁面即可,。
實現(xiàn)代碼,放到當前主題的functions.php中即可(這里還增加了對IP的判斷,,更保險):
// 獲取評論用戶的ip,,參考wp-includes/comment.phpfunction 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ā)表評論 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);