Home > Article > Backend Development > How to Dynamically Update WooCommerce Header Cart Item Count Using Ajax?
Overview:
In Woocommerce, updating the header cart's item count upon adding/removing items can be achieved without page reloads using Ajax.
Solution:
1. HTML Markup for the Cart Count:
In your theme's header.php, add the following code to embed the cart count in an HTML tag with a unique ID or class:
<code class="html"><?php $items_count = WC()->cart->get_cart_contents_count(); ?> <div id="mini-cart-count"><?php echo $items_count ? $items_count : ' '; ?></div></code>
2. Code Implementation:
Next, add this code to your functions.php file or any plugin file:
<code class="php">add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_mini_cart_count'); function wc_refresh_mini_cart_count($fragments){ ob_start(); $items_count = WC()->cart->get_cart_contents_count(); ?> <div id="mini-cart-count"><?php echo $items_count ? $items_count : ' '; ?></div> <?php $fragments['#mini-cart-count'] = ob_get_clean(); return $fragments; }</code>
This hook updates the "mini-cart-count" element with the updated count after adding items to the cart.
3. Optional jQuery Trigger:
If you wish to force the count update via jQuery, use either of these delegated events:
<code class="javascript">$(document.body).trigger('wc_fragment_refresh');</code>
<code class="javascript">$(document.body).trigger('wc_fragments_refreshed');</code>
The above is the detailed content of How to Dynamically Update WooCommerce Header Cart Item Count Using Ajax?. For more information, please follow other related articles on the PHP Chinese website!