How can I log a user out of WordPress before the page loads?

I would am using the code below so that on my wordpress site if ?logout is appended to the end of the URL the user will be logged out. This works well – if the user visits a page such as mysite.com/?logout or mysite.com/test-page/?logout or any page where the $_GET['logout'] variable is set s/he will be logged out.

if( isset($_GET['logout']) ){
    add_action('plugins_loaded', 'wp_logout',0);            
}

The problem I’m facing is that even if I add this action to plugins_loaded, which is at the very top of the list of action hooks, the page that displays will still show the user being logged in. If the page is refreshed on a subsequent load it will display the “logged out” version of the page, but not on the same request.

Read More

Steps to recreate problem:

  1. Add this code to a plugin or perhaps to your functions.php file. I have it in a file in the mu-plugins directory.
  2. Log into your WordPress site.
  3. Visit a page or post on your site, perhaps one with a comments box, and append ?logout to the URL
  4. The page will load as normal, the comments box will have your name and show that you are logged in and can leave a reply
  5. Reload the page (with or without `?login” appended to the url)
  6. The page is now logged out

Desired Behavior

After you are logged in to WordPress visiting a page with ?login appended to the URL will complete the logout process and display the page as if you were logged out when it loads – without having to refresh it.

I don’t think I can hook into WordPress any earlier, and so I’m not sure how to get around this.

Related posts

Leave a Reply

2 comments