問題描述

如何檢查當前登入的使用者是管理員還是編輯者?

我知道如何單獨做

  <?php if( current_user_can('editor')) {  ?>
    stuff here for editors
<?php } ?>
    <?php if( current_user_can('administrator') { ?>
    stuff here for admins
<?php } ?>

但是我如何在一起工作呢?也就是使用者是管理員還是編輯?

最佳解決方案

第一個答案,不是 WordPress 相關因為只是 PHP,使用邏輯”OR” 運運算元:

<?php if( current_user_can('editor') || current_user_can('administrator') ) {  ?>
    // stuff here for admins or editors
<?php } ?>

如果要檢查兩個以上角色,可以檢查當前使用者的角色是否位於角色陣列中,如下所示:

$user = wp_get_current_user();
$allowed_roles = array('editor', 'administrator', 'author');
<?php if( array_intersect($allowed_roles, $user->roles ) ) {  ?>
   //stuff here for allowed roles
<?php } ?>

但是,current_user_can 不僅可以與使用者角色名稱一起使用,還可以使用功能。所以,一旦編輯和管理員都可以編輯頁面,您的生活可以更容易地檢查該功能:

<?php if( current_user_can('edit_others_pages') ) {  ?>
    // stuff here for user roles that can edit pages: editors and administrators
<?php } ?>

看看 here 有關功能的更多資訊。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。