How to get the number of items in cart in WooCommerce

When you develop a custom WooCommerce theme, you have to develop a cart basket section,  where you have to show how many items are currently in the customer’s cart. a freelancer developer has to search solution for it.  here is I will show you how to get the number of items in cart in WooCommerce.
How to get the number of items in cart in WooCommerce

WooCommerce Cart Object

with the WoocCmmerce cart object, you can get full details of the current user’s cart details. like how many items are in the cart, what is the total of the cart is.

$woocart = WC()->cart;

Show How many

you can show how many items are in the cart are, directly accessed by the Woocommerce cart object.

echo WC()->cart->get_cart_contents_count();

More details example is

<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> – <?php echo WC()->cart->get_cart_total(); ?></a>

sometimes we need to update our without refreshing page, Like when customers click on add to cart button we need to update the cart’s total items by ajax, it’s can be done by using simple add_filter hooks. here are snippets for it

 * Show cart contents / total Ajax
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );

function woocommerce_header_add_to_cart_fragment( $fragments ) {
	global $woocommerce;


	<a class="cart-customlocation" href="<?php echo esc_url(wc_get_cart_url()); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> – <?php echo $woocommerce->cart->get_cart_total(); ?></a>
	$fragments['a.cart-customlocation'] = ob_get_clean();
	return $fragments;

you can get more details on the WooCommerce Documentation website.

Add a Comment