skip to Main Content

I’m developing a page that will automatically logout a user as soon as they land on it, then the page will immediately refresh. Once page reloads, the user will be signed out. A similar behaviour is if the user opens the page in Incognito except I want this to happen automatically when they open a link to this page.

I only want this to occur in select pages, I thought a shortcode could be employed to execute the above but can’t get it to work.

I have tried this hook, and then creating a shortcode as per this post except I added the get_permalink function

add_action( 'wp_logout', 'redirect_after_logout');
function redirect_after_logout(){
  wp_redirect( get_permalink() );
  exit();
}

/* Add shortcode */
add_shortcode('logout_and_refresh', 'redirect_after_logout');

but it seems to need to be executed through the logout URL and I want it to happen automatically when the page loads.

<a href="<?php echo wp_logout_url( 'http://redirect-url' ); ?>" title="Logout">Logout</a>

2

Answers


  1. You could call wp_logout() function directly after init / template_redirect hooks.

    https://core.trac.wordpress.org/browser/tags/5.7/src/wp-includes/pluggable.php#L618

    But if you want to execute when document loaded, you could use javascript to redirect to your logout url.

    window.onload = function() {
        var uri = <?php echo json_encode(wp_logout_url( 'http://redirect-url' ));?>;
        location.href = uri;
    };
    
    Login or Signup to reply.
  2. You can use the init action hook for that. first, you need to check is user logged or not. check below code. code will go in active theme function.php file. tested and works.

    add_action( 'init', 'logout_user_land_on_page' );
    function logout_user_land_on_page(){
        if ( is_user_logged_in() ) {
            wp_redirect( wp_login_url() );
            wp_logout();
            exit;   
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search