How to check if the WooCommerce cart is empty

No more empty carts

We had an interesting question the other day from a user who wanted to know if it’s possible to do something only when the WooCommerce cart is empty. WooCommerce core includes several handy methods that can help you out with this, but lots of tutorials show a cart-empty check with the $woocommerce global. However, this is only necessary if working with WooCommerce 2.0 or earlier. You can instead use the WC() global function to cut this down a bit with WooCommerce 2.1 or newer.

We can do our check by using the WC() global function and getting the cart contents count. While there are several ways we could check this, I prefer this method since it returns as an integer, so we simply need to check if it’s equal to zero to determine if the cart is empty.

if ( WC()->cart->get_cart_contents_count() == 0 ) {
        // Do something fun
}

That’s all you need to check if the WooCommerce cart is empty in your own snippet or plugin.

Let’s take a look at a real ucSuppose you want to show a notice in your store if the cart is empty – perhaps this could encourage a promotion or inform customers of coupon codes. It also works really well as a companion to our WooCommerce Cart Notices extension, as this displays notices if items are in the cart.

We’ll create a notice that will only display if there are no products in the cart, and you can determine where you’d like to display the notice (based on which actions you choose to add it to).

/**
 * Tutorial: http://www.skyverge.com/blog/check-if-woocommerce-cart-is-empty/
**/
function skyverge_empty_cart_notice() {
    
	if ( WC()->cart->get_cart_contents_count() == 0 ) {
        	wc_print_notice( __( 'Get free shipping if your order is over $60!', 'woocommerce' ), 'notice' );
        	// Change notice text as desired
	}

}
// Add to cart page
add_action( 'woocommerce_check_cart_items', 'skyverge_empty_cart_notice' );
// Add to shop archives & product pages
add_action( 'woocommerce_before_main_content', 'skyverge_empty_cart_notice' );

Adding the first action will add this to the empty cart template:

WooCommerce Empty Cart Notice | cart

While adding the second action will then display this throughout the rest of the WooCommerce pages, such as the shop archives and product pages.

WooCommerce Empty Cart Notice | shop
WooCommerce Empty Cart Notice | Product

Our notice will display while the WooCommerce cart is empty, then disappear once an item has been added to the cart (which is a great time to let Cart Notices take over!).

Beka Rice is a Sr. Director of Product Management at GoDaddy where she focuses on building an amazing WooCommerce experience. She’s been working with WooCommerce since 2013 and has built dozens of plugins used by hundreds of thousands of online stores.