Snippet

Redirect Users After Login Based on Their Role

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

  1. Just a comment to identify the code.
  2. Declaring the wpt_login_redirect_by_role function. WordPress gives it the address it was going to use, the address that was asked for, and the user who is logging in.
  3. Checking that we really have a logged-in user. When a login fails, WordPress passes an error here instead.
  4. If there is no user, returning the normal address and doing nothing else.
  5. Closing the if statement.
  6. Checking whether the user is an administrator.
  7. If so, sending them to the dashboard with admin_url().
  8. Closing that if statement.
  9. Checking whether the user is a subscriber.
  10. If so, sending them to the /my-account/ page on your website with home_url().
  11. Closing that if statement.
  12. For every other role, keeping the address WordPress picked.
  13. Closing the function.
  14. Adding our function to the login_redirect filter. The 3 tells WordPress our function takes three arguments.