Not every user should be able to log in to the Dashboard, and WooCommerce already prevents this. But you may want to change it for somebody or just use a different page.

By default WooCommerce redirects the user to the My Account page after a successful login.

You can redirect after logging in and use a custom URL based on the user role, like the Dashboard for admins and My Account page for customers.

Add this code at the end of the file functions.php in wp-content/themes/your-child-theme-name/:

<?php
/**
 * Redirect users to custom URL based on their role after login
 *
 * @param string $redirect
 * @param object $user
 * @return string
 */
function wc_custom_user_redirect( $redirect, $user ) {
	// Get the first of all the roles assigned to the user
	$role = $user->roles[0];
	$dashboard = admin_url();
	$myaccount = get_permalink( wc_get_page_id( 'myaccount' ) );
	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 );

Delete the sign <?php on first line if you are having errors come up after saving the file.

If you need to change the URL for a specific role you can use the function get_permalink() passing the page ID to return its URL:

get_permalink( 150 );

This code will return the URL to the page with ID 150.

Advertisements

About the Author Swapnil V. Patil

I make people smile. Not by being funny, No, but by crafting applications and interfaces. I love the web as a platform and is most likely to talk about WordPress, Javascript and Open Source. Here you will find some of my ideas. Enjoy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.