current_user_can()文档中有一句话要注意一下
Do not pass a role name to current_user_can(), as this is not guaranteed to work correctly.
意思是说传递用户角色名称(如author、contributor)作为参数不能100%保证返回正确的结果,正确的用法是传递$capability,从这个函数的表面意思看,参数是权限比参数是角色名称更靠谱。
所以,要根据不同角色拥有的权限来判断用户角色,用户权限可以在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是WordPress的一个全局变量,当用户登录后,这个里面就会有用户的角色和权限信息。
当WordPress的init action执行后,就可以安全的使用$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' );
是因为$current_user这个全部变量到init action执行时才完成赋值,既然要读它的内容,至少要等到它的内容准备好后再读取。functions.php的代码先与init action执行,所以在functions.php中直接写global $current_user是无法获取用户信息的。详细信息可以参考《WordPress Actions加载顺序》。
检查用户角色之前,还可以先检查一下用户是否登录
还有一种更直接的方法,例如判断当前用户是否为管理员
global $current_user; if(in_array( 'administrator', $current_user->roles )){ echo 'administrator'; }
拥有多年WordPress博客/企业建站开发经验,独树一帜的设计,提供最专业的网站设计方案;原创的主题标签语义化,增强网站优化效果。
增强用户体验、提高品牌形象给人留下深刻的印象,那就选择我们,我们的每一款主题都是独一无二的,都有自己的灵魂,每款主题都有各自的配色方案。
遵循现代网页设计的趋势,所有主题都提供完整的响应式布局,优化大桌面显示器以及对平板和智能手机的支持,从而提供一致性的用户体验。
长期及时地在线售后服务和免费升级更新,确保您的网站始终运行在最佳状态,24小时QQ在线的沟通方式免去您的后顾之忧,替您节省网站维护成本。
大王叫我来巡山,我把博客转一转。(*^__^*) 嘻嘻……