Skip Navigation

[Closed] Auto redirect base on the user role

This support ticket is created 3 years, 2 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This topic contains 1 reply, has 2 voices.

Last updated by Nigel 3 years, 2 months ago.

Author
Posts
#2235833

Dear Sir/Madam,

I have the custom role, teacher & student, below is code to redirect them after login

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

function my_login_redirect( $redirect_to, $request, $user ) {
    //is there a user to check?
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        //check for admins
        if ( in_array( 'administrator', $user->roles ) ) {
            return home_url('/wp-admin/');    
        } elseif ( in_array( 'subscriber', $user->roles ) ) {
            return home_url('/welcome/');
        } elseif ( in_array( 'teacher', $user->roles ) ) {
            return home_url('/my-portal/');
        } elseif ( in_array( 'student', $user->roles ) ) {
            return home_url('/student-portal');
        }
        return $redirect_to;
    }
}

It works if I login via the normal WP login form but if I login with social media, it doesn't work. How can I redirect the user to correct landing page according to his custom role no matter he logins via WP login form or social media. I use the plugin Login with Google as the social login.

Best regards,

Kelvin.

#2235889

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

I imagine there might be two things going on here.

Possibly the social login plugin also uses the login_redirect filter, but its code is running after your custom code and overwriting the changes that you make to the $redirect_to url.

In which case you can add a higher priority number to your add_filter call so that the code runs later. To be sure your code runs last, you could change that line to:

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

If that doesn't work then it would suggest that the social login plugin bypasses the normal code so that the login_redirect filter (which is a core WordPress filter) doesn't get run at all.

If that is the case you'll need to ask the social login plugin authors for help. You can explain to them that you are trying to use the login_redirect filter and it works with normal logins but not with social logins via their plugin.

The topic ‘[Closed] Auto redirect base on the user role’ is closed to new replies.