Updating the header cart items count without reloading the page enhances user experience. Let's delve into the problem and its solution.
The goal is to dynamically get the total number of cart items from the server using jQuery. However, the current implementation faces difficulty when multiple items are added simultaneously.
Instead of manual reload, utilize the woocommerce_add_to_cart_fragments action hook, which is powered by Ajax:
<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>
If necessary, force refresh the count using delegated events:
<code class="javascript">$(document.body).trigger('wc_fragment_refresh');</code>
or
<code class="javascript">$(document.body).trigger('wc_fragments_refreshed');</code>
The above is the detailed content of How to Ajaxify Header Cart Items Count in WooCommerce: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!