Advertisement
vapvarun

Capture the referring URL before user navigates to the login page

Dec 13th, 2023
922
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.38 KB | Software | 0 0
  1. // Add to your theme's functions.php or a custom plugin
  2.  
  3. /**
  4.  * Capture the referring URL before user navigates to the login page.
  5.  */
  6. function wbcom_capture_referring_url() {
  7.     // Check if the current page is the WordPress login page and the user is not logged in
  8.     if ( strpos($_SERVER['REQUEST_URI'], 'wp-login.php') !== false && !is_user_logged_in() ) {
  9.         // Get the referrer URL
  10.         $referrer = wp_get_referer();
  11.         // If there's a referrer, store it in a session variable
  12.         if ( !empty($referrer) ) {
  13.             $_SESSION['wbcom_login_referrer'] = $referrer;
  14.         }
  15.     }
  16. }
  17. add_action('wp', 'wbcom_capture_referring_url');
  18.  
  19. /**
  20.  * Redirect user to the previously captured URL after successful login.
  21.  */
  22. function wbcom_redirect_after_login( $redirect_to, $requested_redirect_to, $user ) {
  23.     // Check if our session variable with the referrer URL is set
  24.     if ( isset($_SESSION['wbcom_login_referrer']) ) {
  25.         // Store the URL
  26.         $redirect_url = $_SESSION['wbcom_login_referrer'];
  27.         // Unset the session variable for future logins
  28.         unset($_SESSION['wbcom_login_referrer']);
  29.         // Redirect to the stored URL
  30.         return $redirect_url;
  31.     }
  32.     // If no referrer URL was captured, proceed with the default redirect
  33.     return $redirect_to;
  34. }
  35. add_filter('login_redirect', 'wbcom_redirect_after_login', 10, 3);
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement