Only allow specific user roles to log into site – WordPress

I currently have a WP site setup with a unique ‘multisite’ plugin installed specifically to allow for a single admin area of woocommerce products, but with 2 different front-ends based on 2 different domains, with separate themes.

Anyway, one of the sites is a ‘wholesale’ site while the other is ‘retail’. The wholesale site should only allow trade customers to make purchases. The problem lies in that both sites are sharing a single domain, and therefore user accounts.

The problem: I need to ensure if a user who is does not have the user role ‘trade_customer’ tries to log into the wholesale site, the role is checked and the user is logged out, redirected to login page with a notification. So far I have the following in functions.php:

function trade_customers_only() {
    function get_user_role() {
    global $current_user;

    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);

    return $user_role;

$the_current_role = get_user_role();
echo $the_current_role;
    if( $the_current_role != 'administrator' ) {
       $logout_url = wp_login_url().'?mode=tradeonly';
       wp_redirect( $logout_url, 302 );
 add_action('wp_login', 'trade_customers_only');

function my_login_message() {

    if( $_GET['mode'] == 'tradeonly' ){
        $message = '<p class="message"><b>You must be a Trade Customer to access Key Essentials. Are you looking for <a href="" title="Love Tillys">Love Tillys?</a></b></p>';
        return $message;

 add_filter('login_message', 'my_login_message');

This code is currently: returning the logged in user to wp-login.php and adding the note “You must be a trade customer… etc”. However, after the first login attempt with any user role, every other login attempt does the same redirect and shows message. Is my code incorrect or is there some WP session cookie in the DB or browser causing the problem whereby WP thinks I am not using an admin account?

The first time I attempted login was with admin account. it worked and went to dashboard. Next attempt was with a customer role account. The redirect and note occurred. A following attempt with admin account only did the redirect with note, but no dashboard access…

Please help!

Read more here: Only allow specific user roles to log into site – WordPress

Leave a Reply

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