Skip to content

Instantly share code, notes, and snippets.

@lmartins
Forked from woogist/functions.php
Last active November 3, 2023 19:28
Show Gist options
  • Save lmartins/28186383883d7c5ec644 to your computer and use it in GitHub Desktop.
Save lmartins/28186383883d7c5ec644 to your computer and use it in GitHub Desktop.
By default WooCommerce redirects the user to the My Account page after a successful login. You may change this and use a custom URL based on the user role, like the Dashboard for admins and My Account page for customers. To do this, add this code at the end of the file functions.php located in wp-content/themes/your-theme-name/ https://support.w…
<?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 );
@robertdevore
Copy link

👍

@saintclaire
Copy link

It's Working Perfectly Thanks

@mooneyllc
Copy link

You would think after a user registering it would trigger the same login functions but after registration it goes to my-account page. It works flawlessly when someone who has an account logs in but not a newly registered user.

@rafidesign
Copy link

Hi, this is great thanks - how can I redirect to a custom url?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment