在WordPress主題或者插件開發(fā)的過程中,經(jīng)常要遇到判斷登錄用戶的角色,并根據(jù)不同的用戶角色賦予不同的權(quán)限。下面總結(jié)兩種比較常用的判斷方法。
一、使用 current_user_can() 判斷
current_user_can() 可以根據(jù)不同角色擁有的權(quán)限來判斷用戶角色,具體的用戶權(quán)限,可以在Roles and Capabilities 中找到。
判斷用戶是否為管理員(Administrator)
if( current_user_can( 'manage_options' ) ) {
echo 'The current user is a administrator';
}
判斷用戶是否為編輯(Editor)
if( current_user_can( 'publish_pages' ) && !current_user_can( 'manage_options' ) ) {
echo 'The current user is an editor';
}
判斷用戶是否為作者(Author)
if( current_user_can( 'publish_posts' ) && !current_user_can( 'publish_pages' ) ) {
echo 'The current user is an author';
}
判斷用戶是否為投稿者(Contributor)
if( current_user_can( 'edit_posts' ) && !current_user_can( 'publish_posts' ) ) {
echo 'The current user is a contributor';
}
判斷用戶是否為訂閱者(Subscriber)
if( current_user_can( 'read' ) && !current_user_can( 'edit_posts' ) ) {
echo 'The current user is a subscriber';
}
二、使用$current_user判斷
$current_user是WordPress的一個(gè)全局變量,當(dāng)用戶登錄后,這個(gè)里面就會(huì)有用戶的角色和權(quán)限信息。
當(dāng)WordPress的init action執(zhí)行后,就可以安全的使用$current_user全局變量了。
在模板文件中判斷登錄用戶是否為作者(Author)
global $current_user;
if( $current_user->roles[0] == 'author' ) {
echo 'The current user is an author';
}
在functions.php中判斷用戶是否為作者(Author)
add_action( 'init', 'check_user_role' );
function check_user_role() {
global $current_user;
if( $current_user->roles[0] == 'author' ) {
echo 'The current user is an author';
}
}
之所以要使用
add_action( 'init', 'check_user_role' );
是因?yàn)?current_user這個(gè)全部變量到init action執(zhí)行時(shí)才完成賦值,既然要讀它的內(nèi)容,至少要等到它的內(nèi)容準(zhǔn)備好后再讀取。functions.php的代碼先與init action執(zhí)行,所以在functions.php中直接寫global $current_user是無法獲取用戶信息的。
檢查用戶角色之前,還可以先檢查一下用戶是否登錄
<?php
if( is_user_logged_in() ) {
//用戶已登錄,檢查用戶角色
}
?>
更簡單的方法
還有一種更直接的方法,例如判斷當(dāng)前用戶是否為管理員
global $current_user;
if(in_array( 'administrator', $current_user->roles )){
echo 'administrator';
}





如果需要輸出評論作者的角色應(yīng)該怎么寫
我覺得,這個(gè)地方,還可以講一下 user_can($user_id,'[condition]’); 利用用戶id,來判斷用戶的角色。
—上文提到—↓
"是因?yàn)?current_user這個(gè)全部變量到init action執(zhí)行時(shí)才完成賦值,既然要讀它的內(nèi)容,至少要等到它的內(nèi)容準(zhǔn)備好后再讀取。functions.php的代碼先與init action執(zhí)行,所以在functions.php中直接寫global $current_user是無法獲取用戶信息的。"
———
我想獲取“ 新建文章”的分類,在functions.php判斷,可是如下代碼無效:if ( in_category(‘1’ ) ){//如果在分類1下}
是不是也是要用到init action,我嘗試了,沒起作用。
求教了,謝謝了!!
還有一個(gè)最簡單的user_id,0是游客,1是管理員~
這個(gè)方法太依賴默認(rèn)數(shù)據(jù)了