1

I'm currently using the following code snippet to redirect admins to the admin dashboard and normal users to a specific site upon logging in.

    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 ) ) {
            // redirect them to wp-admin
            return 'https://example.com/wp-admin/';
        } else {
            return 'https://example.com/specific-site/';
        }
    } else {
        return $request;
    }
}

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

What I want to add here is a conditional (probably an elseif?) that when users are logging in from example.com directly, they should be redirected to https://example.com/specific-site/ - however, if they are logging in coming from a specific post (in this case course, because we're using it as an LMS via LearnPress), they should be redirected to that specific post / course after logging in instead.

How would I go about that?

Thanks for your help everyone!

3
  • 1
    This should probably be a two-step mechanism, where on the specific post page, during login, the url of the specific post is passed along with the login data (save the current url in a hidden input in the login form) and then in the redirect section that you posted you can redirect non-admins to that url where they came from – Jos Faber May 12 at 14:15
  • "if they are logging in coming from a specific post" - I think that's just whether $request is set and non-empty. – Rup May 12 at 14:19
  • Thanks! The thing is, I think $request would be example.com/wp-login/ in this case. So I'd need a way to carry over the previous URL (via redirect_to possibly?) to /wp-login/ first and then somehow reuse it in the conditional... Any ideas on how to do this in practice? – cstoll May 12 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.