Home > other >  How to custom redirect users in WordPress without using any plugins
How to custom redirect users in WordPress without using any plugins

Time:11-03

Hi I need a help in redirecting users in my Wordpress website .I want to redirect users to different pages of the website based on their roles. Suppose for a vendor , after login I want to him to redirected to vendor dashboard or for a user like customer I want them to get redirected to custom page, admin will get redirected to admin dashboard , etc. I have tried Peter's login plugin and lots of other plugins to do this but these plugins has lots of limitation plus may lower the speed of the website. Is there anyway we can redirect users to different pages by adding code in the backend

CodePudding user response:

You can do that by using login_redirect hook.

Try out this for your custom redirect user based on their user role:

    function my_login_redirect( $redirect_to, $request, $user ) {
    global $user;
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        $user_roles = $user->roles;
        if ( in_array( 'administrator', $user_roles ) ) {

            $redirect_to = admin_url(); // Admin redirect to admin dashboard.
        }
        if ( in_array( 'vendor', $user_roles ) ) {

            $redirect_to = site_url( 'vendor/dashboard' ); // Custom user redirect accordingly.
        }
    }
    return $redirect_to;
   }

   add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

CodePudding user response:

add_filter('login_redirect', 'login_redirect', 10, 3);

function login_redirect($redirect_to, $requested_redirect_to, $user){
    
    if(!is_wp_error($user) ){

        $user_roles = $user->roles;
        if(in_array('vendor', $user_roles) ){

            $redirect_to = site_url('vendor/dashboard'); //vendor/dashboard update with your dashboard url
        }
        if(in_array('customer', $user_roles) ){

            $redirect_to = site_url('shop'); //any custom page url
        }
    }
    

    return $redirect_to;
}
  • Related