Prevent user creating new users with specific roles

One step is to use the editable_roles filter to remove roles from the dropdown but this doesn’t prevent the user from modifying the select value and create a user with “not allowed” role.

Yes it does. This filter is not just for the dropdown. Modifying editable_roles does in fact prevent users from assigning a role they’re not allowed to.

This is because edit_user() (the function used for adding new users) calls get_editable_roles() as well and bails when one is not allowed to give users that role.

Here’s a simple example of what you can do:

/**
 * Removes Administrator from roles list if user isn't an admin themselves.
 *
 * This way, only admins can make new admins.
 *
 * @param array $all_roles List of roles.
 * @return array Modified list of roles.
 */
function wpse_293133_filter_editable_roles( $all_roles ) {
  if ( ! is_super_admin( get_current_user_id() ) ) {
    unset( $all_roles['administrator'] );
  }

  return $all_roles;
}

add_filter( 'editable_roles', 'wpse_293133_filter_editable_roles' );

Leave a Comment