• Here is a tested solution to redirect users after login to last page before logout.

    // # store the last known URL to session
    function remember_last_page() {
        $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $url = filter_var($referrer, FILTER_SANITIZE_URL);
    
        if(!empty($url)) {
    
            // # Check if session exists, if not start one - PHP 5.4+ required for session_status()
            if (session_status() == PHP_SESSION_NONE) {
                session_name('last_page_visited');
                session_start();
            }
    
            // # prevent looping back to the login page!
            $tld = (stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://'.$_SERVER['HTTP_HOST'].'/' : 'https://'.$_SERVER['HTTP_HOST'].'/');
            if (strpos($url, 'login') === false || $url == $tld) {
                $_SESSION['last_page_visited'] = $url;
            }
        }
    }
    add_action('init', 'remember_last_page');
    
    // # redirect user to last requested page if session contains 'last_page_visited'
    function login_redirect_to_last() {
    
        if(!empty($_SESSION['last_page_visited'])) {
            $url = filter_var($_SESSION['last_page_visited'], FILTER_SANITIZE_URL);
            return $url;
        }
    }
    add_filter( 'login_redirect', 'login_redirect_to_last');

    You can stick this in your functions.php or create a new plugin and install it from the plugin manager.

    Cheers.

Viewing 1 replies (of 1 total)
  • I’ve been searching high and low for exactly this.. for awhile. I placed in functions.php but I am not seeing this work.

    I’m guessing its because I have a membership plugin called Memberpress. Each login is redirected based on the members level to a certain page.

    So when I login in as lets say a free or paid member it takes me to the page I designated.. then if I navigate to another page and log out.. then log in.. I am still taken to the page designated for the redirect in memberpress vs the last page I left..

    Is there anyway you can help me with this or give some pointers on what I need to do to hook this in somehow with memberpress or am I way off on the understanding of how this piece of code works..

    thanks for your time

    EJ

Viewing 1 replies (of 1 total)
  • The topic ‘Login redirect to last page’ is closed to new replies.