How to redirect users after they login based on their role on WordPress

welcome signage on focus photography

If your WordPress site/project needs the users to be redirected to different pages after they successfully login, based on their roles, you can use any of the following plugins:

  1. https://wordpress.org/plugins/role-based-redirect/
    1. Documentation: https://wordpress.org/plugins/role-based-redirect/
  2. https://wordpress.org/plugins/peters-login-redirect/
    1. Documentation: https://loginwp.com/docs/

What about if you want to keep the number of plugins low and do the redirect using custom code?

You can use a snippet as the following one (You can add the code in the functions.php file or in an existing custom plugin):

/**
 * redirect users after they login.
 * @param $redirect_to
 * @param $request
 * @param $user
 * @return mixed|string|void
 */
function my_site_login_redirect( $redirect_to, $request, $user ) {
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        if ( in_array( 'administrator', $user->roles ) || in_array( 'editor', $user->roles ) ) {
            $redirect_to = admin_url();
        } else if ( in_array( 'customer', $user->roles ) ) {
            $redirect_to = home_url( '/shop/' );
        } else {
            $redirect_to = home_url('/shop');
        }
    }
    return $redirect_to;
}
add_filter( 'login_redirect', 'my_site_login_redirect', 10, 3 );

A quick explanation about the code

The code implements the login_redirect filter
The code checks if the user has the admin or the editor role, if so, the user is redirected to the admin dashboard page, else if the user has the vip_customer role, the user is redirected to the /custom-dashboard page, any other users will be redirected to the /shop page.


Posted

in

by