# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Users](https://wpide.com/library/category/users/)
- Tags: roles, users, limits
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/limit-users-per-role/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Limit How Many Users a Role Can Have" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
