Limit How Many Users a Role Can Have
Caps the number of accounts for chosen roles, such as a maximum of 3 Editors, and blocks adding or promoting anyone beyond that limit.
Opens WPIDE on
Code
// Role => maximum number of users.
$wpide_role_limits = array(
'editor' => 3,
'administrator' => 2,
);
$wpide_role_full = function ( $role, $ignore_user = 0 ) use ( $wpide_role_limits ) {
if ( empty( $wpide_role_limits[ $role ] ) ) {
return false;
}
$count = count( get_users( array( 'role' => $role, 'fields' => 'ID', 'exclude' => array( (int) $ignore_user ), 'number' => $wpide_role_limits[ $role ] ) ) );
return $count >= $wpide_role_limits[ $role ];
};
add_action( 'user_profile_update_errors', function ( $errors, $update, $user ) use ( $wpide_role_full ) {
$role = isset( $_POST['role'] ) ? sanitize_key( $_POST['role'] ) : '';
if ( ! $role ) {
return;
}
$current = $update && ! empty( $user->ID ) ? (array) get_userdata( $user->ID )->roles : array();
if ( ! in_array( $role, $current, true ) && $wpide_role_full( $role, $update ? (int) $user->ID : 0 ) ) {
$errors->add( 'wpide_role_full', sprintf( '<strong>Error:</strong> The %s role has reached its user limit.', esc_html( $role ) ) );
}
}, 10, 3 );
// Hide full roles from the role menus.
add_filter( 'editable_roles', function ( $roles ) use ( $wpide_role_full ) {
$editing = isset( $_GET['user_id'] ) ? get_userdata( absint( $_GET['user_id'] ) ) : null;
$keep = $editing ? (array) $editing->roles : array();
foreach ( array_keys( $roles ) as $role ) {
if ( ! in_array( $role, $keep, true ) && $wpide_role_full( $role ) ) {
unset( $roles[ $role ] );
}
}
return $roles;
} );
Notes
Applies when users are added or edited in wp-admin. Existing users above the limit are not demoted.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.