How to filter the role selector?

I know that roles in WordPress are not hierarchical, but I’m wondering if there is any type of capability to “assign users to roles”. All I can see if being able to add users or not.

The real kicker here is, I’ve used Justin Tadlock’s Members plugin to create a new role, called “Clients” which removes all the stuff they should either not need to see, or shouldn’t be able to control – which works great.
But, if I give them the ability to create a new user, they can also choose my “super admin” role, which can see everything. So, in a way, they kinda cheat the system a little bit.

Is there anyway to “hide” a certain role from showing up in what a user can set a new user/edit a user to? Or, possibly remove the role identifier from the add/edit user screen based on their role?
I know it sounds a bit off of what WordPress is mean to do for user permissions, but from an administrative stand-point, it sounds useful – at least in my head 😉

Thanks!

2 Answers
2

The UI select element

On user-edit.php, you see the drop-down in the UI. The drop down <select> wrapper is hard coded.

Then the admin interface does a nifty thing 1) according to the inline comment: // Get the highest/primary role for this user. In fact it is getting the first role, that was assigned to the user (this we have to keep in mind).

Then there’s basically only a call to wp_dropdown_roles(). This function doesn’t do anything else, than looping through the available roles and wrapping them inside <option> elements. But, there’s one kool thing it does: It uses the roles retrieved by get_editable_roles(). And here comes the magic! A filter, for the global $wp_roles->roles. By default this returns all roles, but you can jump in and simply unset whatever you want.

// Add this as mu-plugin
function wpse32738_get_editable_roles( $editable_roles )
{
    if ( current_user_can( 'client' ) )
        // unset whatever you need here.

    return $editable_roles;
}
add_filter( 'editable_roles', 'wpse32738_get_editable_roles' );

1) Roles are a “flat” system. A role can have capabilities that overrule other capabilities.

Leave a Comment