If you simply want the customer to see an empty cart after he logs out, use the following code:
add_filter( 'woocommerce_persistent_cart_enabled', '__return_false' );
However, if you want a logged in user’s cart NOT to persist when he is logged in on different browsers/devices, then you need to use the additional code below. Basically, we need to extend and overide how WooCommerce handles sessions for logged in users. To do this, we need to extend the WC_Session_Handler
and override code relating to logged in users.
class My_Session_Handler extends WC_Session_Handler {
// Make sure all users (regardless of logged in status) are given a random session id
public function generate_customer_id() {
require_once( ABSPATH . 'wp-includes/class-phpass.php');
$hasher = new PasswordHash( 8, false );
return md5( $hasher->get_random_bytes( 32 ) );
}
// Make sure logged in user session id does not change to user id
public function get_customer_unique_id() {
$customer_id = '';
if ( $this->has_session() && $this->_customer_id ) {
$customer_id = $this->_customer_id;
}
return $customer_id;
}
// Make sure logged in user session id does not change to user id
public function init_session_cookie() {
$cookie = $this->get_session_cookie();
if ( $cookie ) {
$this->_customer_id = $cookie[0];
$this->_session_expiration = $cookie[1];
$this->_session_expiring = $cookie[2];
$this->_has_cookie = true;
$this->_data = $this->get_session_data();
// Update session if its close to expiring.
if ( time() > $this->_session_expiring ) {
$this->set_session_expiration();
$this->update_session_timestamp( $this->_customer_id, $this->_session_expiration );
}
} else {
$this->set_session_expiration();
$this->_customer_id = $this->generate_customer_id();
$this->_data = $this->get_session_data();
}
}
}
//Hook in our session handler
if ( ! is_admin() ) {
add_action( 'after_setup_theme', function() {
add_filter( 'woocommerce_session_handler', function() {
return 'My_Session_Handler';
});
});
}
The above might be useful if you want to give a group of users a single log in credential for a private shop. In this way, the users will see different carts on their respective browsers even though they are logged in using the same user credential.
Updated as of WordPress 5.8 and WooCommerce 5.5.2.