I know how to direct logged out user to a particular page or a URL, like:
<a href="https://wordpress.stackexchange.com/questions/184731/<?php echo wp_logout_url( home_url() ); ?>">Log out</a>
But if I want the user to redirect to the URL where he/she just was, what can I do?
Though I’m not knowledgeable about wp_get_referer()
, but I tried:
<?php $redirect_to = wp_get_referer() ? wp_get_referer() : home_url(); ?>
<a href="https://wordpress.stackexchange.com/questions/184731/<?php echo wp_logout_url( $redirect_to ); ?>">Log out</a>
and
<?php $redirect_to = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : home_url(); ?>
<a href="https://wordpress.stackexchange.com/questions/184731/<?php echo wp_logout_url( $redirect_to ); ?>">Log out</a>
with no luck. 🙁
It’s always taking me to the home_url()
.
1 Answer
You get the current path with remove_query_arg( '' )
. Combine it with site_url()
, and you have the full current request URI:
$url = untrailingslashit( site_url() );
$url .= remove_query_arg( '' );
Be aware that remove_query_arg()
doesn’t return a sanitized value, so you have to use esc_url()
if you want to print it to a page. Otherwise, someone could inject malicious code into your site in an URL parameter.
wp_get_referer()
is for form submissions, it looks for a request parameter _wp_http_referer
and is not relevant in your case.