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:
- Improves user experience.
- Keeps cart count synchronized.
- Works with WooCommerce AJAX add-to-cart functionality.
- Lightweight and easy to customize.
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;
}