You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress按角色层级限制用户列表可见范围的实现问询

实现WordPress用户列表按角色权限层级展示的方案

这个需求确实不需要依赖第三方插件,通过WordPress的内置钩子就能轻松实现,而且扩展性很强,支持自定义角色的层级配置。我给你写一套完整的代码方案,你可以直接用:

1. 定义角色权限层级

首先我们需要把所有角色(包括默认角色和你添加的自定义角色)按权限从高到低分配层级数值,数值越大权限越高:

function get_role_hierarchy() {
    return [
        'administrator' => 5,   // 最高权限
        'editor' => 4,          // 编辑
        'author' => 3,          // 作者
        'contributor' => 2,     // 贡献者
        'subscriber' => 1,      // 订阅者
        // 在这里添加你的自定义角色,比如:
        // 'senior_author' => 3.5,  // 高级作者,层级在作者和编辑之间
        // 'custom_subscriber' => 0.5, // 自定义订阅者,权限低于默认订阅者
    ];
}

2. 编写用户查询过滤逻辑

用pre_get_users钩子修改后台用户列表的查询结果,让每个用户只能看到权限层级比自己低的用户(管理员不受限制):

function restrict_user_list_by_role_hierarchy($query) {
    // 只在后台用户列表页面生效,避免影响其他查询
    if (!is_admin() || !$query->is_main_query() || get_current_screen()->id !== 'users') {
        return;
    }

    $current_user = wp_get_current_user();
    if (empty($current_user->roles)) {
        return;
    }

    // 获取当前用户的最高权限层级(处理用户有多个角色的情况)
    $role_hierarchy = get_role_hierarchy();
    $current_highest_level = 0;
    foreach ($current_user->roles as $role) {
        if (isset($role_hierarchy[$role]) && $role_hierarchy[$role] > $current_highest_level) {
            $current_highest_level = $role_hierarchy[$role];
        }
    }

    // 管理员可以查看所有用户,直接返回
    if (in_array('administrator', $current_user->roles)) {
        return;
    }

    // 收集所有权限层级低于当前用户的角色
    $allowed_roles = [];
    foreach ($role_hierarchy as $role => $level) {
        if ($level < $current_highest_level) {
            $allowed_roles[] = $role;
        }
    }

    // 设置查询条件,只展示允许的角色用户
    if (!empty($allowed_roles)) {
        $query->set('role__in', $allowed_roles);
    } else {
        // 如果没有允许查看的角色,返回空结果
        $query->set('role__in', ['nonexistent_role']);
    }
}
add_action('pre_get_users', 'restrict_user_list_by_role_hierarchy');

3. 调整自定义角色层级

如果你添加了自定义角色,只需要在get_role_hierarchy函数里给它分配合适的数值就行——比如你有一个senior_editor角色,权限比默认editor高、比administrator低,就给它设为4.5,这样它就能查看editor、author、contributor、subscriber这些层级更低的用户。

4. 代码放置位置

把上面两段代码复制到你当前主题的functions.php文件里,或者创建一个简单的自定义插件来存放(推荐后者,避免主题更新丢失代码)。

可选调整

如果你需要让用户能查看和自己角色相同的用户,只需要把代码里的$level < $current_highest_level改成$level <= $current_highest_level就行,这样编辑就能看到其他编辑了,完全符合你一开始描述的“展示与自身角色相同或权限层级更低的用户”需求。

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:14:34