Cleanup session in WooCommerce

There are some pretty simple ways to clear a session with WooCommerce that can be used with code when you need a user to get a brand new session with nothing old getting in the way. Can be used if you by code set a country or currency that’s not the WooCommerce default for example.

The most brutal (and sometimes most officiant way) is to destroy the session completely.

WC()->session->destroy_session()

https://woocommerce.github.io/code-reference/classes/WC-Session-Handler.html#method_destroy_session

This line cleans the session and clears the cookies for you and should be called early in WordPress since it tampers with cookies and session variables. For example:

// clear WC session if argument do_cleanup is true is passed
add_action( 'wp_loaded', 'my_cleanup_session');
function my_cleanup_session() {
  if ($_REQUEST['do_cleanup'] == 'true') {
    // cleanup old session
    WC()->session->destroy_session();
    // force redirect (needed in some cases) 
    //wp_safe_redirect( '/' );
  }
}

There are other alternatives as well if you don’t need to completely destroy the session. You could try one of these instead:

// clears session, but keeps cookies
WC()->session->cleanup_session()

// clear specific users session
WC()->session->delete_session($customer_id)

// forgets the session without destroying it
WC()->session->forget_session()

Check here for more details in the code reference.

Comments

Cart