Allow or restrict specific user roles to login
|

Allow or restrict specific user roles to log into WordPress site

In WordPress when you want to remove the access for a specific user, you can simply delete that user or change the role. In some cases, you might want to just revoke the user’s access without completely deleting the user. For Example: If you have a user role for Employees as “Active Employee” and “Inactive Employee”, then in the case of “Inactive Employee” you might not want Employee to Login to the website.

The below code will make sure that “Inactive Employee” will not be able to Login to the site.

//Remove Access of Inactive Employee

add_filter( 'authenticate', 'activeusers_check', 100, 1 );

function activeusers_check( $user ) {
    if ( !is_wp_error($user) ) {
        $user_role = $user->roles[0];
        /* Do not forget to replace inactive_employee with the user role or multiple roles for which you want to remove access. You can add multiple roles in array by separating them with comma */
        if ( in_array( $user_role, array( 'inactive_employee' ) ) ){
            return new WP_Error( 'authentication_failed', __( "Only Active Employees can login to site" ) );
        } else {
            // allow the login
            return $user;   
        }
    } else {
        
        return $user;       
    }
}   

You can add the above code in the functions.php file of your theme or use the code snippets plugin. After adding the above code, when a user with the user role “inactive_employee” will try to log in to the site, he will be redirected back to the login page with an error.

Above code snippet works good but if user is already Logged into the site in his browser then changing role will not Log him out of the site although he might lose access to content based on restrictions set by you. Don’t worry, with a small code snippet we can Logout all the users with specific role from WordPress website so already Logged in users will get logged out automatically on accessing site next time.

I hope this article has helped you to learn how to Allow or restrict specific user roles to log into WordPress site. If you have any questions, feel free to ask in the comments.

Similar Posts

Leave a Reply

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