欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

WordPress中限制非管理員用戶(hù)在文章后只能評(píng)論一次

 更新時(shí)間:2015年12月31日 14:14:48   作者:露兜  
這篇文章主要介紹了WordPress中限制非管理員用戶(hù)在文章后只能評(píng)論一次的方法,同時(shí)介紹了判斷用戶(hù)是否為管理員的方法,需要的朋友可以參考下

之前有網(wǎng)友提出,在WordPress中有沒(méi)有辦法實(shí)現(xiàn)每篇文章只允許用戶(hù)評(píng)論一次?

暫不說(shuō)這個(gè)需求有沒(méi)有用,畢竟WordPress就是給有各種需求的人用的。這個(gè)功能實(shí)現(xiàn)起來(lái)也比較簡(jiǎn)單,只需每次用戶(hù)發(fā)表的評(píng)論進(jìn)數(shù)據(jù)庫(kù)之前,從當(dāng)前文章的所有評(píng)論中查找是否有相同的用戶(hù)名或郵箱已經(jīng)發(fā)表過(guò)評(píng)論,如果有就跳到錯(cuò)誤頁(yè)面即可。

實(shí)現(xiàn)代碼,放到當(dāng)前主題的functions.php中即可(這里還增加了對(duì)IP的判斷,更保險(xiǎn)):

// 獲取評(píng)論用戶(hù)的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);

這里沒(méi)有限制管理員的評(píng)論次數(shù),那我們順帶著看一下判斷用戶(hù)是否為管理員的方法:

判斷指定id的用戶(hù)是不是管理員

該需求實(shí)現(xiàn)起來(lái)非常簡(jiǎn)單,幾行代碼搞定,分享一下:

function ludou_is_administrator($user_id) {
 $user = get_userdata($user_id);
 if(!empty($user->roles) && in_array('administrator', $user->roles))
  return 1; // 是管理員
 else
  return 0; // 非管理員
}

判斷當(dāng)前登錄用戶(hù)是不是管理員

如果是判斷當(dāng)前登錄用戶(hù)是不是管理員,可以使用下面的函數(shù):

function ludou_is_administrator() {
 // wp_get_current_user函數(shù)僅限在主題的functions.php中使用
 $currentUser = wp_get_current_user();

 if(!empty($currentUser->roles) && in_array('administrator', $currentUser->roles)) 
  return 1; // 是管理員
 else
  return 0; // 非管理員
}

相關(guān)文章

最新評(píng)論