2

Basically I want to write some code that decided wether to redirect a User to the Home page of the website or to the page that the user came from prior to logging in.

I have this code which successfully redirects users to the page they came from if a redirect back to that page has been specified. However, if there is no specific redirect request, users are sent to the backend admin panel.

<?php
function login_redirect( $redirect_to, $request, $user ) {

    if (isset($user->roles) && is_array($user->roles)) {

        if (in_array('subscriber', $user->roles)) {

            if($request){
                $redirect_to = $request;
            } else {
                $redirect_to =  home_url();
            }

        }
    }

    return $redirect_to;
}

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

How can I tweak this so that the users don't get to see the admin panel?

2

OK, so let's take a deeper look, how this hook is used in WP... It's fired up in wp-login.php (on line 901):

$requested_redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
// ...
$redirect_to = apply_filters( 'login_redirect', $redirect_to, $requested_redirect_to, $user );

So, the variable you called $request (which is a little bit misleading, it should be called $requested_redirect_to) should be empty, so your code should work just fine. But... There's always a but ;)

If you'll got o wp-login.php and take a closer look at login form, then you'll see, that there is a hidden input called redirect_to in it and it contains URL of wp-admin. So this condition if($request){ is always true.

You can fix it this way:

function login_redirect( $redirect_to, $requested_redirect_to, $user ) {
    if ( isset($user->roles) && is_array($user->roles) ) {

        if ( in_array('subscriber', $user->roles) ) {

            if ( $requested_redirect_to && admin_url() != $requested_redirect_to ) {
                $redirect_to = $requested_redirect_to;
            } else {
                $redirect_to =  home_url();
            }

        }
    }
    return $redirect_to;
}
add_filter( 'login_redirect', 'login_redirect', 10, 3 );
| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.