In WooCommerce, displaying the number of items in the cart in the header is essential for user navigation. When these items change (added or removed), it's desirable to update the cart count without reloading the page using JavaScript (specifically Ajax).
To obtain the current cart count from PHP using Ajax, we need to create a dedicated file, such as reloadCart.php, that echoes this count.
<code class="php"><?php require('../../../wp-blog-header.php'); global $woocommerce; echo $woocommerce->cart->get_cart_contents_count(); ?></code>
Next, in our JavaScript code, we can retrieve this count using the $.get() function:
<code class="js">$(".ajax_add_to_cart").click(function () { $.get("<?php echo get_template_directory_uri(); ?>/reloadCart.php", function(data){ console.log("Cart Count: " + data); }); });</code>
However, using $.get() for this purpose is not the recommended approach in WooCommerce.
WooCommerce provides a dedicated woocommerce_add_to_cart_fragments action hook specifically designed for updating the cart content count in Ajax.
Register the Action Hook:
<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>
Update the HTML to Refresh:
<code class="html"><div id="mini-cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></div></code>
Now, when the ajax_add_to_cart button is clicked, the woocommerce_add_to_cart_fragments action hook will automatically update the #mini-cart-count HTML element with the refreshed count.
To force refresh the count using jQuery, use the wc_fragment_refresh or wc_fragments_refreshed delegated events:
<code class="js">$(document.body).trigger('wc_fragment_refresh'); // or wc_fragments_refreshed</code>
The above is the detailed content of How to Refresh WooCommerce Header Cart Item Count Using Ajax?. For more information, please follow other related articles on the PHP Chinese website!