After logging in, WordPress takes every user to the dashboard. That makes sense for admins and editors, but a subscriber or a customer has nothing to do there. It is much nicer to send them straight to a useful page, like their account page or a members area. You can do that based on the role of the user using the following code. If you are working on the login screen too, have a look at our guide to customize the WordPress login page.
Where to place? functions.php of your child theme, or a code snippets plugin.
Usage
- To send subscribers or customers to their account page instead of the dashboard.
- On membership websites, to take members straight to the members-only area.
- To keep admins going to the dashboard while everybody else lands on the website.
Code
// Redirect users to different pages after login, based on their role
function wpt_login_redirect_by_role( $redirect_to, $requested_redirect_to, $user ) {
if ( ! $user instanceof WP_User ) {
return $redirect_to;
}
if ( in_array( 'administrator', (array) $user->roles, true ) ) {
return admin_url();
}
if ( in_array( 'subscriber', (array) $user->roles, true ) ) {
return home_url( '/my-account/' );
}
return $redirect_to;
}
add_filter( 'login_redirect', 'wpt_login_redirect_by_role', 10, 3 );
Replace /my-account/ with the page you want subscribers to land on. You can add more if blocks for other roles, such as editor, author or customer (the role WooCommerce gives shoppers).
Explanation
- Just a comment to identify the code.
- Declaring the
wpt_login_redirect_by_rolefunction. WordPress gives it the address it was going to use, the address that was asked for, and the user who is logging in. - Checking that we really have a logged-in user. When a login fails, WordPress passes an error here instead.
- If there is no user, returning the normal address and doing nothing else.
- Closing the if statement.
- Checking whether the user is an administrator.
- If so, sending them to the dashboard with
admin_url(). - Closing that if statement.
- Checking whether the user is a subscriber.
- If so, sending them to the
/my-account/page on your website withhome_url(). - Closing that if statement.
- For every other role, keeping the address WordPress picked.
- Closing the function.
- Adding our function to the
login_redirectfilter. The3tells WordPress our function takes three arguments.