WordPress中限制非管理使用者在文章後只能評論一次,wordpress_PHP教程

來源:互聯網
上載者:User

WordPress中限制非管理使用者在文章後只能評論一次,wordpress


之前有網友提出,在WordPress中有沒有辦法實現每篇文章只允許使用者評論一次?

暫不說這個需求有沒有用,畢竟WordPress就是給有各種需求的人用的。這個功能實現起來也比較簡單,只需每次使用者發表的評論進資料庫之前,從當前文章的所有評論中尋找是否有相同的使用者名稱或郵箱已經發表過評論,如果有就跳到錯誤頁面即可。

實現代碼,放到當前主題的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();  // 不限制管理員發表評論 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('本站每篇文章只允許評論一次。點此返回'); }  return $commentdata;}add_action( 'preprocess_comment' , 'ludou_only_one_comment', 20);

這裡沒有限制管理員的評論次數,那我們順帶著看一下判斷使用者是否為管理員的方法:

判斷指定id的使用者是不是管理員

該需求實現起來非常簡單,幾行代碼搞定,分享一下:

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; // 非管理員}

判斷當前登入使用者是不是管理員

如果是判斷當前登入使用者是不是管理員,可以使用下面的函數:

function ludou_is_administrator() { // wp_get_current_user函數僅限在主題的functions.php中使用 $currentUser = wp_get_current_user(); if(!empty($currentUser->roles) && in_array('administrator', $currentUser->roles))   return 1; // 是管理員 else  return 0; // 非管理員}

您可能感興趣的文章:

  • 詳解WordPress中建立和添加過濾器的相關PHP函數
  • WordPress中用於建立以及擷取側邊欄的PHP函數講解
  • WordPress中給媒體檔案添加分類和標籤的PHP功能實現

http://www.bkjia.com/PHPjc/1087280.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1087280.htmlTechArticleWordPress中限制非管理使用者在文章後只能評論一次,wordpress 之前有網友提出,在WordPress中有沒有辦法實現每篇文章只允許使用者評論一次?...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.