You should not use any reload to update the cart content count… Instead you should use the dedicated woocommerce_add_to_cart_fragments
action hook that is Ajax powered.
1) The HTML to be refreshed: So first in your theme’s header.php
file you should need to embed the cart count in a specific html tag with a defined unique ID (or a class), for example something like:
$items_count = WC()->cart->get_cart_contents_count();
?>
<div id="mini-cart-count"><?php echo $items_count ? $items_count : ' '; ?></div>
<?php
or:
$items_count = WC()->cart->get_cart_contents_count();
echo '<div id="mini-cart-count"><?php echo $items_count ? $items_count : ' '; ?></div>';
2) The code:
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;
}
if you use a class in your html Tag, you will replace ['#mini-cart-count']
by ['.mini-cart-count']
. This hook is also used to refresh the mini-cart content.
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Since few years
global $woocommerce;
+$woocommerce->cart
is outdated and replaced byWC()->cart
to access WooCommerce cart object.
If you need jQuery to force refresh that count, you can try wc_fragment_refresh
or wc_fragments_refreshed
delegated events, like:
$(document.body).trigger('wc_fragment_refresh');
or:
$(document.body).trigger('wc_fragments_refreshed');