Identifying the Need
In WooCommerce integrated WordPress themes, updating the header cart items count without reloading the page is a common challenge. jQuery offers a solution, but questions arise when items can be added in multiple quantities.
Utilizing AJAX to Retrieve Total Count
To dynamically retrieve the total cart count from PHP sessions using jQuery, a reloadCart.php file is created to echo the value:
<code class="php"><?php require('../../../wp-blog-header.php'); global $woocommerce; echo $woocommerce->cart->get_cart_contents_count(); ?></code>
AJAX Implementation
However, attempts to make AJAX calls to this file using jQuery's get(), post(), or ajax() functions have been unsuccessful.
Improved Approach
Instead of relying on a reload, WooCommerce offers a dedicated woocommerce_add_to_cart_fragments action hook that supports Ajax.
HTML Integration
Embed the cart count in the header with a unique ID or class:
<code class="php">$items_count = WC()->cart->get_cart_contents_count(); ?> <div id="mini-cart-count"><?php echo $items_count ? $items_count : '&nbsp;'; ?></div> <?php
PHP Code
Implement the following code in the theme's function.php file or a plugin:
<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 : '&nbsp;'; ?></div> <?php $fragments['#mini-cart-count'] = ob_get_clean(); return $fragments; }</code>
Replace #mini-cart-count with .mini-cart-count if using a class.
jQuery Refresh
If additional jQuery refresh is required:
<code class="php">$(document.body).trigger('wc_fragment_refresh');</code>
or
<code class="php">$(document.body).trigger('wc_fragments_refreshed');</code>
The above is the detailed content of How to Dynamically Update WooCommerce Header Cart Items Count Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!