Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.