WooCommerce redirect on login

woocommerce-redirect

When using WooCommerce on your WordPress website, typical login and logout redirects code snippets will stop working. This is because WooCommerce has it’s own redirect hook and will take priority over the normal WordPress redirects.

However, one can use the following snippet to redirect users to specific URL depending on user role.

/**
* Redirect users to custom URL based on their role after login
*
*/
function wc_custom_user_redirect( $redirect, $user ) {
// Get the first of all the roles assigned to the user
$role = $user->roles[0];

// Variables
$dashboard = admin_url();
$myaccount = get_permalink( wc_get_page_id( 'myaccount' ) );
$shop = get_permalink( wc_get_page_id( 'shop' ) );

if( $role == 'administrator' ) {
//Redirect administrators to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'shop-manager' ) {
//Redirect shop managers to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'editor' ) {
//Redirect editors to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'author' ) {
//Redirect authors to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'customer' || $role == 'subscriber' ) {
//Redirect customers and subscribers to the "My Account" page
$redirect = $myaccount;
} else {
//Redirect any other role to the previous visited page or, if not available, to the home
$redirect = wp_get_referer() ? wp_get_referer() : home_url();
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );

We have added three common redirect destinations the dashboard, my-account and the shop pages for the various default users roles within WordPress.

To change the destination for a specific user role, simple change the variable on the redirect for the user roles if statement.

If you would like to add a redirect for a custom user role, you can copy a if statement within the function, and change the $role variable to match your custom role.

elseif ( $role == 'change-to-custom-role' ) {
//Redirect custom role to the dashboard
$redirect = $dashboard;
} 

The last part of the function within the “else” statement will direct the user to the previous referral page or to the home page. This will affect people who are unable to log in or if they are not assigned to a user role covered here. If you want to direct these users to the shop page, replace the else statement with the following.

else {
//Redirect any other role to the previous visited page or, if not available, to the home
$redirect = wp_get_referer() ? wp_get_referer() : $shop;
}

Nicholas Duell Avatar

Leave a Reply

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