How to set a limit of 1 user to custom user role?

I am trying to create an user role, say Developer and want to limit user by 1. So if one user is added by admin through WP Admin then no more users can be added to this user role.

I was able to add user role with admin capabilities:

add_action('init', 'clone_admin');
function clone_admin()
{
 global $wp_roles;
 if (!isset($wp_roles))
    $wp_roles = new WP_Roles();

    $adm = $wp_roles->get_role('administrator');
    // Adding a new role with all admin caps.
    $wp_roles->add_role('developer', 'Developer', $adm->capabilities); 

}

I have tried the below code to limit the user:

function count_users_wp() {
 $users_query = new WP_User_Query( array(
                'blog_id' => get_current_blog_id(),
                'role'         => 'developer',
            ) );
    return $users_query->get_total();
}
function limit_users_register() {
    $count = apply_filters('limit_user_count',1);
    $users = count_users_wp();    
    if ($users >= 1) { //Check if total users exceeds 
        update_option('users_can_register',0);  //Disable registration
    }else{
        update_option('users_can_register',1);  //Enable registration
    }

}
add_action('user_register','limit_users_register');


function limit_user_register($option) {
    remove_filter('pre_option_users_can_register','limit_user_register');
    $reg = get_option('users_can_register');
    if (0 === $reg) {
        return 0; //break
    }
    $count = apply_filters('limit_user_count',1);
    $users = count_users_wp();
    if ($users >= $count) {
        update_option('users_can_register',0); //Disable registration
        return 0;
    } else {
        update_option('users_can_register',1); //proceed to registration
        return $option;
    }
}
add_filter('pre_option_users_can_register','limit_user_register');

Please advise. Thank You

Read more here: How to set a limit of 1 user to custom user role?

Leave a Reply

Your email address will not be published. Required fields are marked *