Block user(s) from log in to WordPress website without need for dedicated plugin

Need to block user? We had some inquires how to block (malicious) users from WordPress powered websites. There are plugins for this purpose but we prefer simple ways for doing simple tasks. Here is code snippet for your functions.php that will do the job (how to use code snippets).

/**
 * 
 * User login blocking without need for dedicated plugin.
 * 
 */
function wpgenie_check_attempted_login( $user, $username, $password ) {

    
    $blocked = array( 1, 2, 3 ); // user IDs you want to block


    if ( is_a ( $user, 'WP_User' ) ) {

        if ( !in_array( $user->ID, $blocked) ) {
                
            return $user;

        } else {

            $user = new WP_Error(
                'account_locked',
                'Your account has been locked. Please contact us for assistance.'
            );
            
            return $user;
        }
    }     
}

add_filter('authenticate', 'wpgenie_check_attempted_login', 100, 3);

This code only prevents blocked users from log in. If they are allready logged in, they will stay logged in until auth cookies are deleted, after that they will not be able to login again.

Code can be found on our Pastebin here.