最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
WordPress中判断用户是不是管理员的教程
时间:2015-09-01 编辑:简简单单 来源:一聚教程网
今天在写个小程序,需要判断指定用户的角色是不是网站管理员,如知道用户的id是123,想要知道他是不是管理员。
一、判断指定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各个用户组所对应的级别,那么我们需要来判断是否为管理员,也就是Administrator
我们就用level_10。判断代码就如下
if(current_user_can('level_10')){
//加入符合管理员后需要添加的内容
}这样想判断其他级别的用户也就是换个级别就可以了。
利用这个我们就可以做出很多对应各个用户组的对应功能。
补充:
一、使用 current_user_can() 判断
current_user_can() 可以根据不同角色拥有的权限来判断用户角色,具体的用户权限,可以在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的一个全局变量,当用户登录后,这个里面就会有用户的角色和权限信息。
当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是无法获取用户信息的。
检查用户角色之前,还可以先检查一下用户是否登录
if( is_user_logged_in() ) {
//用户已登录,检查用户角色
}
?>
更简单的方法
还有一种更直接的方法,例如判断当前用户是否为管理员
global $current_user;
if(in_array( 'administrator', $current_user->roles )){
echo 'administrator';
}
相关文章
- WordPress屏蔽非法关键词用户名的方法 10-08
- HTML简单购物数量小程序代码展示 10-31
- html canvas实现弹幕功能 10-31
- HTML中空格表示的意义 10-31
- html area标签解读 10-31
- html使用表单标签实现注册页面代码展示 10-31