WooCommerce: Redirect Users by Role to Specific URL After Login

Blog

Posted by Nuno Marques on 8 Apr 2020

WooCommerce: Redirect Users by Role to Specific URL After Login

Tutorial

Visitor

This snippet is perfect for scenarios where you want to restrict access to the backend, such as during website development or maintenance. By assigning the "Subscriber" role to designated users and implementing the provided code in thefunctions.php file of your child theme, you can redirect them to a specific URL upon login, effectively blocking backend access.

function visitor_login_redirect( $redirect_to, $request, $user ) {
    // Is there a user to check?
    if (isset($user->roles) && is_array($user->roles)) {
        // Check for subscribers
        if (in_array('subscriber', $user->roles)) {
            // Redirect them to another URL
            $redirect_to = 'https://example.com';
        }
    }

    return $redirect_to;
}

add_filter( 'login_redirect', 'visitor_login_redirect', 10, 3 );

Shop Manager

For scenarios where you want to grant access to both the frontend and backend to specific users, such as clients or shop managers, the provided snippet allows you to redirect users with the "Shop Manager" role to a specific WooCommerce page upon login. This ensures a seamless transition to the relevant backend section for managing orders.

function shop_manager_login_redirect( $redirect_to, $request, $user ) {
    // Is there a user to check?
    if (isset($user->roles) && is_array($user->roles)) {
        // Check for shop managers
        if (in_array('shop_manager', $user->roles)) {
            // Redirect them to another URL
            $redirect_to = 'https://example.com/wp-admin/edit.php?post_type=shop_order';
        }
    }

    return $redirect_to;
}

add_filter( 'login_redirect', 'shop_manager_login_redirect', 10, 3 );

Conclusion

By implementing these snippets, you can efficiently manage user access and tailor the login experience for different roles on your WooCommerce website. Whether you need to restrict backend access during development or streamline backend navigation for specific user roles, these solutions offer flexibility and control.

This post was tagged in: