My redirect function in functions.php has this structure--
//After Login Redirection
function my_login_redirect( $redirect_to, $request, $user ) {
$user_id = (isset($user->ID) ? $user->ID : false);
$urlparameters = $_SERVER['QUERY_STRING'];
$decode = urldecode($urlparamiters);
preg_match('~=(.*?)&~',$decode, $redirecturl);
//If the paramiter redirect_to is found in the url then run the url redirect.
if(strpos($urlparameters, "redirect_to")!== false) {
return $redirecturl[1];
} else {
//If no redirect in the URL then use standard redirect according to roles
if (isset($user->roles) && is_array($user->roles)) {
if (in_array('administrator', $user->roles)) {
//is this the administrator?
$redirect_to = home_url( $path = '/wordpress/wp-admin/', $scheme = 'https' );
}
elseif (in_array('client', $user->roles)) {
// Take clients to the private messaging board
$redirect_to = home_url( $path = '/wordpress/pm/', $scheme = 'https' );
}
}
return $redirect_to;
}
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
WHAT I WANT AND WHAT I GET
When customers access my site it is either directly from the wp-login.php page or because they have been sent to a specific page. If sent to a specific page the url will contain a log in redirect parameter. If the url has a parameter starting with "redirect_to" I only want to run that redirect. If there is not parameter in the URL I want to run my standard redirect sequence. The above code does not work. It is only running my standard redirection routine. So, my first IF condition is not working and I am not sure why.
WHAT I HAVE TRIED AND WHAT I SEE
When I land on the login page, If I echo back $urlparameters I can see they are being caught accurately. If I echo back $decode and $redirecturl[1] I see the values I expect. However I hit the login button, the function runs as if the $urlparameters, $decode, and $redirecturl[1] variables are empty.
If I use a redirect URL, and I remove the second IF condition (disable the ability to use the standard redirect) customers are directed to their WordPress profile screen. So it is as if $redirecturl[1] is just empty. If I make $redirecturl[1] the only option for redirect the same happens (no conditions). If I keep the second IF condition in place, the code runs as if no parameters are in the URL and the standard redirects are completed.
The error log produces Undefined offset: 1 for $redirecturl[1] indicating that it is empty. And yet I see a value when I echo the variable.
Please help me understand the following:
Why are my variables ($urlparameters, $decode, and $redirecturl[1]) echoing back the expected values but are functioning as if they are empty when I hit the login button. How can I correct this?
Am I losing the session data because I have hit the login button? If so, how can I maintain the data into the next screen?