How to Clear Cart on Logout In WooCommerce

WooCommerce Clear Cart on Logout

If you want to clear your cart on logout in WooCommerce, this post will guide you on how you can add a quick snippet to your WooCommerce theme and achieve this.

In most cases when users log in or log out the items in the cart are not removed. In the instance you want to achieve this, you need to add a custom code to your functions.php file as you will see below.

In the last few posts, I shared how you can create a WooCommerce login logout shortcode and also the ultimate guide for WooCommerce logout redirect.

You can use the tips shared on those two posts to enhance your user’s logout experience along with the code here on how to clear the cart on logout.

WooCommerce Clear Cart on Logout

If you want the cart to clear on logout you should add the following code snippet to your functions.php file :

<?php //callback function
function njengah_woocommerce_clear_cart_logout() {
if( function_exists('WC') ){
WC()->cart->empty_cart();
}
}
//Hook
add_action('wp_logout', 'njengah_woocommerce_clear_cart_logout');

How Does this Code Work?

This code is an action hook with a callback function that gets the WooCommerce object and calls the empty cart function to execute during the WooCommerce logout event.

If you run into any problems with this code, I can help get it added to your site without breaking your site.

Conclusion

In this post, we have looked at how you can add a code snippet to your functions.php file to clear the cart when the users log out.

Similar Articles

Comments are closed.