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:
-
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). -
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.