Home > Article > Backend Development > How to Ajaxify Header Cart Items Count in WooCommerce?
Ajaxify Header Cart Items Count in WooCommerce
Challenge
In a custom WooCommerce-integrated WordPress theme, an issue arose where a cart items count indicator displayed incorrect values after adding items. The culprit was adding a specific quantity of items to the cart, resulting in the indicator only incrementing by one.
Solution
To address this, we can leverage WooCommerce's dedicated woocommerce_add_to_cart_fragments action hook, which provides Ajax support for updating the cart items count.
Implementation
1. HTML and ID/Class
In the theme's header.php file, we define the HTML element that will display the cart count. It's important to assign a unique ID or class for easy targeting:
<code class="html"><div id="mini-cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></div></code>
2. PHP Code
Next, we add a function to the functions.php file that uses the hook to update the cart count content dynamically:
<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>
3. Ajax Update
If you require additional control with jQuery, consider using the wc_fragment_refresh or wc_fragments_refreshed events:
<code class="javascript">$(document.body).trigger('wc_fragment_refresh');</code>
or
<code class="javascript">$(document.body).trigger('wc_fragments_refreshed');</code>
By implementing these changes, the cart items count indicator will accurately reflect the number of items in the cart, even when adding specific quantities of products.
The above is the detailed content of How to Ajaxify Header Cart Items Count in WooCommerce?. For more information, please follow other related articles on the PHP Chinese website!