Prevent Editors from Editing/Deleting Admin Accounts

I need editors to be able to add/edit/delete other users. Giving them those capabilities is easy with code similar to this:

$editor = get_role('editor');
$editor->add_cap('edit_users');

The problem is that when they have the privileges they need to add/edit/delete other users, they can also do all of those things to admin users and/or promote themselves to the admin role.

Read More

Is there a way to allow them to add/edit/delete only specified user roles (best case scenario)? Or as an alternative, prevent editors from doing anything at all to admin accounts, and possibly even hide those accounts from their list view altogether?

Related posts

Leave a Reply

1 comment

  1. There is a function WordPress uses called get_editable_roles, which is (I think) used to determine which roles a particular user can edit. The source for this function looks like this:

    function get_editable_roles() {
        global $wp_roles;
    
        $all_roles = $wp_roles->roles;
        $editable_roles = apply_filters('editable_roles', $all_roles);
    
        return $editable_roles;
    }
    

    So, it looks like you may be able hook into the *editable_roles* filter to get what you’re looking for. Something like this:

    function wpse_80220_filter( $roles ) {
        $current_user = wp_get_current_user();
    
        if ( in_array( 'editor', $current_user->roles ) ) {
            unset( $roles['administrator'] );
        }
    
        return $roles;
    }
    add_filter( 'editable_roles', 'wpse_80220_filter' );
    

    I haven’t tested any of the above code, but play with it and let me know if it does the trick!