Skip to main content
Login Join
Snippet · PHP

Refresh Header Cart Count Using WooCommerce AJAX Fragments

Shared by Naman Chauhan · June 2, 2026 · @woocommerce_add_to_cart_fragments

27 views
4 upvotes
Back to Snippets

When products are added to the cart via AJAX, custom cart counters in the theme header do not automatically update. This snippet uses the woocommerce_add_to_cart_fragments filter to refresh the cart count dynamically without requiring a page reload.

Benefits:

add_filter( 'woocommerce_add_to_cart_fragments', 'custom_cart_fragments' );

function custom_cart_fragments( $fragments ) {

	ob_start();
	?>
	<span class="cart-count">
		<?php echo WC()->cart->get_cart_contents_count(); ?>
	</span>
	<?php
	$fragments['span.cart-count'] = ob_get_clean();

	ob_start();
	?>
	<span class="cart-subtotal">
		<?php echo WC()->cart->get_cart_subtotal(); ?>
	</span>
	<?php
	$fragments['span.cart-subtotal'] = ob_get_clean();

	return $fragments;
}
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments