How do you log a user out with wp_logout?

I can get wp_logout to work, but not without generating lots of warnings (‘PHP warning: Cannot modify header information – headers already sent’).

wp_logout calls wp_clear_auth_cookie, which calls setcookie, and the cookies have to go with the HTTP headers. I’m calling wp_logout inside the page (in the header or footer), hence the problem.

So, how exactly am I meant to programmatically log a user out? I could do this in response to an ajax request, but that seems way over the top. Thanks.

EDIT

Current code as follows:

add_action('wp_footer', 'fp_onload_php2');
function fp_onload_php2() {
   $slug = basename(get_permalink());
   if($slug != 'club-login')
      return;

   $jsmsg    = '';
   $loggedin = false;
   if(is_user_logged_in()) {
      $current_user = wp_get_current_user();
      $loggedin = $current_user->has_cap('customer');
   }

   if($loggedin && isset($_GET['logout'])) {
      wp_logout();
      $jsmsg    = 'You have been logged out.';
      $loggedin = false;
   } else if(!$loggedin && isset($_GET['logout']))
      $jsmsg = "You are not logged in.";

   if(!$loggedin)
      echo
         "<script type="text/javascript"> fp_onload_js2(0, '" . $jsmsg .
         "'); </script>\n";
   else
      echo
         "<script type="text/javascript"> fp_onload_js2(1, '" . $jsmsg .
         "'); </script>\n";
}  // fp_onload_php2()

2 Answers
2

If you’re using wp_logout in your own code, its probably best to exit or wp_redirect immediately afterwards.

You can call wp_set_current_user(0) after wp_logout() to manually log the user out instantly, if you need to continue executing PHP but don’t want the user to be logged in.

Leave a Comment