Home » After Login Redirect To Previous Page In WordPress

After Login Redirect To Previous Page In WordPress

Last updated on May 27, 2022 by

Sometimes, It is required to redirect users back to the page they were viewing before logging in. There could be a plugin for this but we are not suggesting to use a plugin for small things. So that we have created a code snippet that will help you after login redirect to previous page in WordPress. Let’s just dive into it.

Table of Contents
1. An Ideal Place to Add Code in WordPress
2. Why We Should Do Login Redirect To Previous Page?
3. Two Steps For Login Redirect To The Previous Page
3.1. Capture Last Page URL in WordPress
3.2. After Login Redirect User To The Last Page

An Ideal Place to Add Code in WordPress

Most Important: Add the following code to your child theme’s functions.php file. If you add custom code directly to your parent theme’s functions.php file then it will be wiped entirely when you update the theme.

If you are using a custom theme and if it doesn’t require any update then you can directly place the code into wp-content/themes/your-theme/function.php file.

Please also note that we have tested all codes in the GeneratePress child theme & Storefront child theme.

Why We Should Do Login Redirect To Previous Page?

Normally, people are not drawing enough attention to the smallest things. After login redirection to the previous page is a very small thing but it’s very effective for a great user experience.

Some sites might have very tricky navigation and hard-to-find pages so when a user comes to the site and try to access any pages but they can’t access pages due to login restrictions. So they will log in to the site and try to find the same page which gives a wrong impression of your site. Instead, we can add simple code that will automatically capture the page before login and it will automatically redirect to the page they were viewing before logging in.

Two Steps For Login Redirect To The Previous Page

We can achieve this via simple 2 steps:

  • First, we need to capture the page they were viewing before logging in.
  • The second is to redirect the user to the last or previous page.

Let’s just do it.

01 Capture Last Page URL in WordPress

In the following code, we have used the wp action hook. This is one effective place to perform any high-level filtering or validation, following queries, but before WordPress does any routing, processing, or handling.

Simply, the following code will set the last visited page URL into the session variable on each page visit.

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function is_login_page() {
    return in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'));
}

add_action( 'wp', 'sc_capture_before_login_page_url' );
function sc_capture_before_login_page_url(){
    if( !is_user_logged_in() && !is_login_page()):
    	$_SESSION['referer_url'] = get_the_permalink();
    endif;
}

02 After Login Redirect User To The Last Page

In the following code, we have used the login_redirect filter hook. As the name suggests, this hook is helpful to change the login redirect URL.

So we will fetch the URL that we captured in the above code snippet and return it to the filter. That’s it.

/*@ After login redirection */
if( !function_exists('sc_after_login_redirection') ):
    function sc_after_login_redirection($redirect_to, $request, $user) {
 		
	    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
		    if ( isset($_SESSION['referer_url']) ):
		        $redirect_to  = $_SESSION['referer_url'];
		        unset( $_SESSION['referer_url'] );
		    endif;

		    if (session_status() === PHP_SESSION_NONE) {
			    session_write_close();
			}
	    }

	    return $redirect_to;
   }
   add_filter('login_redirect', 'sc_after_login_redirection', 10, 3);
endif;

Additionally, read our guide:

  1. How to Add Products Per Page Dropdown in WooCommerce
  2. “Sorry, your session has expired. Return to homepage” – WordPress WooCommerce Error
  3. How to Create a Plugin in WordPress from Scratch
  4. How to Disable Admin Bar in WordPress Without Plugin
  5. How To Send Custom Emails in WordPress
  6. How to Allow Preview of Draft Post Without Login in WordPress
  7. Import Users From CSV In WordPress Programmatically
  8. Dynamically Populate A Select Field’s Choices In ACF

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

 
 

33 thoughts on “After Login Redirect To Previous Page In WordPress”

  1. I have been checking out many of your articles and i can state pretty nice stuff. I will surely bookmark your site. Fancy Hugh Brandy

    Reply
  2. Hi Scrathcode Team, thanks a lot for that snippet.

    I have a use case that is a bit different and I’d like to use a modified version of your code (except that I’m not a coder).

    What I’d like to do is:
    – by default, redirect the user to a specific page of my site (the user dashboard)
    – or redirect him/her to the last page seen if he/she was already on my site before logging in (on the classic wp-login.php page).

    Would you add this scenario to your article or create a specific article for this use case? 🙂

    Reply
    • Hey Laurent,

      We are happy that you are taking look at our articles, Your second point already satisfied by our current article. Let’s say you want to visit the “Funds” page but it requires login and after the login, it will redirect you to the “Funds” page.

      We can’t understand your first point, can you please elaborate a little more so that we can understand. Moreover, let us know that the second point is working for you or not because all the codes are tested properly and after that, we posted on the site.

      Thanks 🙂

      Reply
  3. Very interesting post.
    Unfortunately, it doesn’t run on my site.
    I pasted the two snippets in my child theme function.php
    Any idea of this disappointment?

    Reply
  4. If you want this code to work in 2022, add session_start(); before the filter and function and replace get_the_permalink(); with wp_get_referer();

    See full modification I made below that got this code to work for me:

    session_start();

    add_action( 'wp', 'sc_capture_before_login_page_url' );
    function sc_capture_before_login_page_url(){
    if( !is_user_logged_in() ):
    $_SESSION['referer_url'] = wp_get_referer();
    endif;
    }

    /*@ After login redirection */
    if( !function_exists('sc_after_login_redirection') ):
    function sc_after_login_redirection() {

    $redirect_url = home_url('/');
    if ( isset($_SESSION['referer_url']) ):
    $redirect_url = $_SESSION['referer_url'];
    unset( $_SESSION['referer_url'] );
    endif;

    return $redirect_url;
    exit;
    }
    add_filter('login_redirect', 'sc_after_login_redirection');
    endif;

    Reply
    • This works for me, but with wp debug enabled is gives the follwoing warning:

      Warning: Use of undefined constant ‘wp’ - assumed '‘wp’' (this will throw an Error in a future version of PHP) in …/wp-content/themes/wp-base/functions.php on line 163

      Warning: Use of undefined constant ‘sc_capture_before_login_page_url’ - assumed '‘sc_capture_before_login_page_url’' (this will throw an Error in a future version of PHP) in …/wp-content/themes/wp-base/functions.php on line 163

      Warning: Use of undefined constant ‘sc_after_login_redirection’ - assumed '‘sc_after_login_redirection’' (this will throw an Error in a future version of PHP) in …/wp-content/themes/wp-base/functions.php on line 171

      Warning: Use of undefined constant ‘login_redirect’ - assumed '‘login_redirect’' (this will throw an Error in a future version of PHP) in…/wp-content/themes/wp-base/functions.php on line 183

      Warning: Use of undefined constant ‘sc_after_login_redirection’ - assumed '‘sc_after_login_redirection’' (this will throw an Error in a future version of PHP) in …/wp-content/themes/wp-base/functions.php on line 183

      Reply
  5. It worked but Site Health gave this critical warning…

    An Active PHP Session Was Detected
    A PHP session was created by a session_start() function call. This interferes with REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.

    Where should you add the session_write_close() ?

    Reply
  6. Hi – Thanks for this bit of code

    It works well when I’m using the regular wp-login.php, but I want to use a custom login page with the url /login and it doesn’t work with this.

    I assume I need to add the custom page to the array here:

    function is_login_page() {
    return in_array($GLOBALS[‘pagenow’], array(‘wp-login.php’, ‘wp-register.php’));
    }

    What should I add? I’ve tried ‘login’ and that doesn’t work

    Hope you can help

    Vik

    Reply
    • Hey Vik,

      I think you can add the following code for that


      function is_login_page() {
      global $pagename;

      if ($pagename === 'login') {
      return true;
      }
      return false;
      }

      Replace your page name in the “if” condition if it’s different than “login”. Hope it helps

      Reply
  7. Hi

    First, thanks a lot for this site… it’s got me out of a few sticky situations – really useful as I’m just learning PHP and I need a lot of help.

    I’m using this new version of the code, but I still get the site health warnings that David2 mentions above, about an active PHP session being detected.

    I also find that when I’m testing it I always get redirected to the same post that I was on the first time I tested it instead of the one I came from, which I guess makes sense if it still thinks I’m in the same open session

    I’ve searched around a lot for the answer but everything I read seems to lead here, so apologies for repeating my previous comment

    Vik

    Reply

Leave a Comment