Block user login

If you need to block user login at WordPress, especially if you wish to block login for the group of users, you may assign them special empty role, created with the help of “User Role Editor”. Let’s name it “block-login”, for example. “Empty” means that role does not contain any capability. Role Editor include the ‘read’ capability into new role by default. Turn it off in order to get empty role. It’s easy, right? But user with empty role will see the message “You do not have sufficient permissions to access this page” at empty grey background after every login try.
Is it possible to make this blocking more user friendly, if this action could be named user friendly at all? The answer is “Yes”.
Add code below to your active theme file functions.php:

add_filter( 'authenticate', 'my_authenticate', 30, 3 );
function my_authenticate( $user, $username, $password ) {    
    if ($user instanceof WP_User && user_can($user, 'block-login')) {
        return new WP_Error(1, 'Login is prohibited');
    }
    return $user;
}

It’s done. After input valid user name and password users with role ‘block-login” will see this error message at the login page:

login prohibited
login prohibited

In case you need to block more then one role, use this modified version of code:

add_filter( 'authenticate', 'myplugin_auth_signon', 30, 3 );
function myplugin_auth_signon( $user, $username, $password ) { 
    if ($user instanceof WP_User) { 
        $roles_to_block = array('block-login', 'block-login1', 'block-login2');
	foreach($roles_to_block as $role_to_block) {
	  if (user_can($user, $role_to_block)) {
	      return new WP_Error(1, 'Login is prohibited');
	  }
	}
    }
    return $user;
}

Just replace the names of dummy roles at the line #4 to that you wish to block.

Share