2

I am trying to give more permissions to the editor role by giving it access to create user accounts. See the code below. But I would like to prevent it from creating or editing existing users with the role of administrator.

function add_theme_caps() {
    $role = get_role('editor');
    $role->add_cap( 'edit_theme_options' );
    $role->add_cap('list_users');
    $role->add_cap('create_users');
    $role->add_cap('delete_users');
    $role->add_cap('edit_users');
}
add_action( 'admin_init', 'add_theme_caps');

Things I am trying to achieve.

  1. The list_users option lists all the users. I would like to list only the non-admin users.
  2. I want to limit this role from creating new user accounts with the role of administrator and also prevent it from change the role of any existing users to an administrator.

1 Answer 1

4

Imho that's one of the most important things regarding users:

/**
 * Deny access to 'administrator' for other roles
 * Else anyone, with the edit_users capability, can edit others
 * to be administrators - even if they are only editors or authors
 * 
 * @since   0.1
 * @param   (array) $all_roles
 * @return  (array) $all_roles
 */
function deny_change_to_admin( $all_roles )
{
    if ( ! current_user_can('administrator') )
        unset( $all_roles['administrator'] );

    if ( 
        ! current_user_can('administrator')
        OR ! current_user_can('editor')
    )
        unset( $all_roles['editor'] );

    if ( 
        ! current_user_can('administrator')
        OR ! current_user_can('editor')
        OR ! current_user_can('author')
    )
        unset( $all_roles['author'] );

    return $all_roles;
}
function deny_rolechange()
{
    add_filter( 'editable_roles', 'deny_change_to_admin' );
}
add_action( 'after_setup_theme', 'deny_rolechange' );
4
  • Hi @kaiser I came across the following solution wordpress.stackexchange.com/questions/4479/… and I was wondering if your logic of only overriding the editable roles was enough or a check for each map_meta_cap was also required to prevent any unauthorized edits. – Arpit Jacob 7 hours ago Feb 24, 2012 at 10:32
  • I'm no friend of intercepting the map_meta_cap stuff, because the sky could fall on your head. But maybe it's in this case done well. I don't know as I didn't try it. Remember only one thing: function naming in the linked Q is only this way, because it's in a class used as namespace.
    – kaiser
    Feb 24, 2012 at 10:38
  • Do you know why any solution still allows editors to create administrator users? Jun 8, 2015 at 14:26
  • @ArmelLarcier Please ask a separate question (see How to Ask for a how to) and explain why you want to do that.
    – kaiser
    Jun 8, 2015 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.