Search code examples
phpwordpressbrowserbrowser-cache

Brower back button issue in wordpress after logout


I am using the below redirect code in the functions.php file.

add_action('wp_logout','auto_redirect_after_logout');
function auto_redirect_after_logout(){
   $adfsurllogouturl = 'some url';
   wp_redirect( $adfsurllogouturl );exit();
}

It's working fine. The issue is that once logged out, it redirects to SOMEURL when I click on the back button of the browser from the redirected page, it shows previous page details. But I want that it should go on the login page.

I used the below code to fix it but it's not working.

function check_if_user_is_loggedin_action()
{
    if ( is_user_logged_in() ) 
    {
        header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
    }
}
add_action('init', 'check_if_user_is_loggedin_action');

Please suggest to me. Is it the correct way?


Solution

  • I have resolved my problem as follows.

    I added a cookie in the functions.php file just after logging in.

    function login_function() {
        setcookie('wp_user_logged_in', 1, time() + 31556926, '/');
        $_COOKIE['wp_user_logged_in'] = 1;
    }
    add_action('wp_login', 'login_function');
    

    I deleted and set the cookie value to NULL in the functions.php file just after logout.

    add_action('wp_logout','auto_redirect_after_logout');
    function auto_redirect_after_logout(){
      unset($_COOKIE['wp_user_logged_in']);
      setcookie('wp_user_logged_in', null, -1, '/');
      wp_safe_redirect( '/login-page' );
      exit();
    }
    

    Added following javascript in footer.php file to check the user is logout and reload the page.

    <script type="text/javascript">
        setInterval(function(){         
            if (document.cookie.indexOf('wp_user_logged_in') !== -1) {
                //do something when user logged in
            } else {
                //do something when user logged out
                window.location.reload();//reload page
            }
        },2000);
    </script>