钩子文档

editable_roles

💡 云策文档标注

概述

editable_roles 是一个 WordPress 过滤器,用于过滤用户可编辑的角色列表,主要应用于 get_editable_roles() 函数中,控制哪些角色可以被当前用户分配给其他用户。

关键要点

  • 过滤器名称:editable_roles,应用于 get_editable_roles() 函数返回的角色数组。
  • 参数:$all_roles,一个包含角色信息的数组数组,用于修改可编辑角色列表。
  • 使用场景:在用户屏幕的批量操作和资料屏幕中显示可分配角色,要求用户具有 edit_users 能力。
  • 相关函数:get_editable_roles(),位于 wp-admin/includes/user.php,用于获取当前用户可编辑的角色列表。
  • 版本历史:自 WordPress 2.8.0 引入。

代码示例

// 示例1:过滤掉比当前用户级别更高的角色
add_filter('editable_roles', 'remove_higher_levels');
function remove_higher_levels($all_roles) {
    global $current_user;
    $next_level = 'level_' . ($current_user->user_level + 1);
    foreach ( $all_roles as $name => $role ) {
        if (isset($role['capabilities'][$next_level])) {
            unset($all_roles[$name]);
        }
    }
    return $all_roles;
}

// 示例2:添加“无角色”选项(在非用户资料屏幕)
add_filter('editable_roles', 'add_empty_editable_role');
function add_empty_editable_role($all_roles) {
    global $pagenow;
    if ('profile.php' != $pagenow) {
        $all_roles[''] = array(
            'name' => __('— No role for this site —'),
            'capabilities' => array(),
            );
    }
    return $all_roles;
}

📄 原文内容

Filters the list of editable roles.

Parameters

$all_rolesarray[]
Array of arrays containing role information.

More Information

editable_roles is a filter applied by the function get_editable_roles() to the list of roles that one user can assign to others (a user must have the edit_users capability to change another user’s role). This list is displayed in the bulk operations (if the user has the list_users and promote_users) of the Users Screen, and on the profile screen.

Source

$editable_roles = apply_filters( 'editable_roles', $all_roles );

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example migrated from Codex:

    Filter out roles with levels higher than the current user’s:

    add_filter('editable_roles', 'remove_higher_levels');
    
    user_level + 1);
    
        foreach ( $all_roles as $name => $role ) {
            if (isset($role['capabilities'][$next_level])) {
                unset($all_roles[$name]);
            }
        }
    
        return $all_roles;
    }

  2. Skip to note 4 content

    Example migrated from Codex:

    Add a “No role” option that sets users’ roles to nothing on pages other than the user profile screen (where it already exists):

    add_filter('editable_roles', 'add_empty_editable_role');
    
    id)) {
            $all_roles[''] = array(
                'name' => __('— No role for this site —'),
                'capabilities' => array(),
                );
        }
    
        return $all_roles;
    }