在 WordPress 主题或者插件开发的过程中,经常要遇到判断登录用户的角色,并根据不同的用户角色赋予不同的权限。下面总结两种比较常用的判断方法。
一、使用 current_user_can() 判断
current_user_can() 可以根据不同角色拥有的权限来判断用户角色,具体的用户权限,可以在 Roles and Capabilities 中找到。
判断用户是否为管理员(Administrator)
1 2 3 4 | //判断用户是否为管理员(Administrator) if( current_user_can( 'manage_options' ) ) { echo 'The current user is a administrator'; } |
判断用户是否为编辑(Editor)
1 2 3 4 | //判断用户是否为编辑(Editor) if( current_user_can( 'publish_pages' ) && !current_user_can( 'manage_options' ) ) { echo 'The current user is an editor'; } |
判断用户是否为作者(Author)
1 2 3 4 | //判断用户是否为作者(Author) if( current_user_can( 'publish_posts' ) && !current_user_can( 'publish_pages' ) ) { echo 'The current user is an author'; } |
判断用户是否为投稿者(Contributor)
1 2 3 4 | //判断用户是否为投稿者(Contributor) if( current_user_can( 'edit_posts' ) && !current_user_can( 'publish_posts' ) ) { echo 'The current user is a contributor'; } |
判断用户是否为订阅者(Subscriber)
1 2 3 4 | //判断用户是否为订阅者(Subscriber) if( current_user_can( 'read' ) && !current_user_can( 'edit_posts' ) ) { echo 'The current user is a subscriber'; } |
二、使用$current_user 判断
$current_user 是 WordPress 的一个全局变量,当用户登录后,这个里面就会有用户的角色和权限信息。
当 WordPress 的 init action 执行后,就可以安全的使用$current_user 全局变量了。
在模板文件中判断登录用户是否为作者(Author)
1 2 3 4 5 | //在模板文件中判断登录用户是否为作者(Author) global $current_user; if( $current_user->roles[0] == 'author' ) { echo 'The current user is an author'; } |
在 functions.php 中判断用户是否为作者(Author)
1 2 3 4 5 6 7 8 | //在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'; } } |
之所以要使用
1 | add_action( 'init', 'check_user_role' ); |
是因为$current_user 这个全部变量到 init action 执行时才完成赋值,既然要读它的内容,至少要等到它的内容准备好后再读取。functions.php 的代码先与 init action 执行,所以在 functions.php 中直接写 global $current_user 是无法获取用户信息的。
检查用户角色之前,还可以先检查一下用户是否登录
1 2 3 4 5 6 | //检查用户是否登录 <?php if( is_user_logged_in() ) { //用户已登录,检查用户角色 } ?> |
三、更简单的方法
还有一种更直接的方法,例如判断当前用户是否为管理员
1 2 3 4 5 | //判断当前用户是否为管理员 global $current_user; if(in_array( 'administrator', $current_user->roles )){ echo 'administrator'; } |