How to Redirect Users Back to the Referring Page After Login in WordPress

WPTurbo » Snippets » How to Redirect Users Back to the Referring Page After Login in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Have you ever wanted to set up your website in such a way that your users are redirected back to the page they were visiting before they logged in? This level of customization can greatly improve the user experience, as it saves users the trouble of navigating back to their original page post-login. This article provides a step-by-step guide on how to redirect users back to the referring page after login in WordPress. Get ready to take your user navigation to the next level.

					function wpturbo_redirect_back_to_referring_page() {
     if (isset($_SERVER['HTTP_REFERER'])) {
        wp_safe_redirect($_SERVER['HTTP_REFERER']);
        exit;
     }
}
add_action('wp_login', 'wpturbo_redirect_back_to_referring_page');
				

The majority of this code snippet revolves around defining a new function, which we are calling wpturbo_redirect_back_to_referring_page(). This particular function has a specific purpose: it will redirect users back to the page from which they have come after they log into WordPress.

Within the function, we find an if statement that checks whether the HTTP_REFERER value is set in the $_SERVER superglobal array. The HTTP_REFERER server variable holds information about the page that led the user to the current page.

if (isset($_SERVER['HTTP_REFERER'])) { ... }

This condition essentially asks, "Is there a referring page to redirect to?" If the answer is yes, the subsequent code within the conditional’s block executes.

wp_safe_redirect($_SERVER['HTTP_REFERER']);
exit;

Here we are using WordPress’s wp_safe_redirect() function to redirect the user securely. This method uses wp_validate_redirect() to ensure the redirect does not lead to an external URL, unless such URLs are specifically whitelisted, making it safer.

We pass $_SERVER['HTTP_REFERER'] to the function, which is the URL from which the user came. After setting the redirect header, the exit statement terminates the current script’s execution. This is done to prevent WordPress from continuing to load after setting the headers.

Finally, after declaring and defining our function, we hook it to the wp_login action:

 add_action('wp_login', 'wpturbo_redirect_back_to_referring_page');

This means that our redirection function will be triggered whenever the wp_login action is fired, which typically happens right after a successful login. The resulting behavior is a redirect back to the page where the user was before logging in.

Register an account to save your snippets or go Pro to get more features.