Woocommerce condition if cart is empty

A user recently asked us an intriguing question about whether it was feasible to perform a specific action only when the WooCommerce cart was empty. There are a number of helpful methods in the WooCommerce core that can assist you with this, but many tutorials demonstrate a cart-empty check using the $woocommerce global. However, if using WooCommerce 2.0 or a previous version, this is just necessary. With WooCommerce 2.1 or newer, you can utilise the WC() global function to reduce this a little.

Using the global function WC() and the count of the cart’s items, we can do our check. There are a number of ways we might check this, but I prefer this approach because it returns an integer, thus all we need to do to see if the cart is empty is check if it equals zero.

if ( WC()->cart->get_cart_contents_count() == 0 ) {
// your code here
}

You just need that information to determine whether the WooCommerce cart is empty in your own snippet or plugin.

Let’s examine a genuine uc.If the cart is empty, let’s say you want to display a notification in your store. This can stimulate a promotion or alert customers to coupon codes. It also complements our WooCommerce Cart Notices extension quite well, which shows notices if things are in the cart.

You can select where you’d want to display the message (depending on the actions you choose to add it to), and it will only appear if there are no products in the cart.

function coderazaa_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’, ‘coderazaa_empty_cart_notice’ );
// Add to shop archives & product pages
add_action( ‘woocommerce_before_main_content’, ‘coderazaa_empty_cart_notice’ );

 

The shop archives and product pages, as well as the rest of the WooCommerce pages, will then display this after adding the second action.

Once an item is placed to the WooCommerce cart, our message will no longer be visible, making it the perfect opportunity to let Cart Notices take over.

 

 

People also search
Scroll to Top