Ajax Powered Cart Items Count In WooCommerce

Sayan Dey

Sayan Dey / January 10, 2023

2 min read––– views

In WooCommerce, it's possible to use AJAX to update the number of items in a user's cart without requiring the page to be reloaded.

This can be useful for creating a more seamless shopping experience for your customers.

Here is an example of how you might use AJAX to update the cart item count in WooCommerce:

1

Add the following code to your theme's functions.php file.

This code should be added to the functions.php file of your active WordPress theme. It hooks into the woocommerce_add_to_cart_fragments filter and updates the #cart-count element with the number of items in the cart.

add_filter( 'woocommerce_add_to_cart_fragments', 'ajax_add_to_cart_fragment' );

function ajax_add_to_cart_fragment( $fragments ) {
	ob_start();
	$fragments['#cart-count'] = '<span id="cart-count">' . WC()->cart->get_cart_contents_count() . '</span>';
	ob_get_clean();
	return $fragments;
}
2

Add HTML element to WordPress theme.

Finally, in your WordPress theme's header.php you need to add HTML element to show the cart item count, that id should be cart-count for example, something like:

<span id="cart-count"></span>

When the visitor add an item to the cart, it triggers the added_to_cart event, which in turn triggers the AJAX request to update the cart item count. This allows the visitor to see the number of items in your cart.

Conclusion

I hope this helps! Let me know if you have any questions on Guestbook. Subscribe to my weekly newsletter for more WordPress tutorials like this.

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.

- subscribers – View all issues