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 );