1

What I'm after is to simply redirect a user to the referring URL after they have logged in. I've been trying to figure this out for a few days now and I've read everything I possibly can, but either the posts I find are 4-5 years old or whatever posted code I try doesn't seem to work.

I'm on a multisite and would prefer something that would be applied to all subsites, but for now, I can settle with something that modifies each site individually.

Here's the latest I've tried which is code that I found somewhere but this continues to redirect the user to their profile on the admin side.

function redirect_after_login() {
    $refer=urlencode($_SERVER["REQUEST_URI"]);
    global $redirect_to;
    if (!isset($_GET['redirect_to'])) {
        $redirect_to = $refer;
    }
}
add_action('login_form', 'redirect_after_login');

If anyone could point me in the right direction, that would be great!

  • Does your site use domain mapping? If so what plugin or code. Also, I'm not sure $redirect_to is a global reference. – Nathan Powell Nov 29 '16 at 5:59
  • 1
    Actually this code looks a bit squirrelly. There is no else to release the global, nor a proper return. – Nathan Powell Nov 29 '16 at 6:02
  • You never set any redirect_to in your function parameters. That is required. Check it here: codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect – Nathan Powell Nov 29 '16 at 6:05
  • So is a return value – Nathan Powell Nov 29 '16 at 6:07
  • Yes.. using WPMU DEV's Domain mapping plugin. – Shayne H. Nov 29 '16 at 6:10
1

Your code is completely flawed - not to mention you can't redirect to the HTTP referer after login... because the referer is now the login page. Instead, use the login_redirect filter:

add_filter( 'login_redirect', function ( $redirect_to, $requested_redirect_to ) {
    if ( ! $requested_redirect_to ) {
        $redirect_to = wp_get_referer();
    }

    return $redirect_to;
}, 10, 2 );

Note that we only override $redirect_to if $requested_redirect_to is "empty", otherwise:

  1. It will break the redirect_to URL parameter that both WordPress and many plugins use to set specific post-login redirects other than the default (too many times have I seen plugins completely break this feature).

  2. If we always set it to the referer, we'll end up with the login page itself (as mentioned earlier). This is because when a user first lands on the login page, WordPress sets a hidden redirect_to field with the value of $redirect_to. On subsequent page load (i.e. logging in), this becomes the $requested_redirect_to value.

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.