You want to redirect the user to the page they were viewing before logging in. There may be a plugin that supports this, but I don’t think it’s a good idea to install multiple plugins on the site.
I will show you a piece of code to help with this. Let’s start with me!

Contents
Why redirect to the page the user is viewing before logging in?
Often, we don’t pay enough attention to the smallest things. Redirecting to the page the user is viewing before logging in is a very small thing that gives a great user experience.
Archive last page before login
The code below will store the last page the user viewed, before they logged in. I will use SESSION in PHP to store the URL of the page.
add_action( 'wp', 'hk_store_url_before_login' );
function hk_store_url_before_login() {
session_start();
if ( ! is_user_logged_in() ) {
$_SESSION['referer_url'] = $_SERVER["HTTP_REFERER"];
}
}
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span>
</div>
User redirect after login
In the code below, I will use hook login_redirect . As the name implies, this hook will support redirecting the user after login.
So I will return the URL stored in the SESSION in the above step into this hook. You add this code below the code in the above step in the functions.php file .
function hk_after_login_redirection() {
$redirect_url = home_url('/');
if ( isset( $_SESSION['referer_url'] ) ) {
$redirect_url = $_SESSION['referer_url'];
unset( $_SESSION['referer_url'] );
}
return $redirect_url;
}
add_filter( 'login_redirect', 'hk_after_login_redirection' );
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>
Epilogue
It is done! A simple yet extremely useful tip to improve the user experience on your website. If you found this article helpful, please comment and share this article.
In addition, you can follow the WordPress Tips section and follow Facebook for more new knowledge.

