You know the drill; you add your own custom cart count into the header of your new theme. You add an item to the cart via AJAX. The cart count doesn’t update. Not good!

The problem; you haven’t told WooCommerce to update it. Fortunately, it’s easy to hook into the method that updates the default cart count and cart contents (like the mini cart widget), and add your own items to update on the page. You can do all of this via some very simple PHP code, without even touching javascript.

This is something you could implement if you’re using our WooCommerce Quickview plugin. It’ll already update the default fragments for you, but it’s easy to add your own.

Template Code

Let’s say you’ve added an element in your header that displays the total cart count, like so:

<div class="header-cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></div>

This is perfect for displaying the cart count on page load, but won’t update after adding to cart via AJAX; on the archive pages, for example.

Update Cart Count After AJAX

You can simply add your HTML data to the cart fragments that are returned. To expand on this; WooCommerce already returns cart fragments (HTML data) on page load and every time something is added to the cart via AJAX. This replaces the contents of the mini cart, and other elements on the page. It’s a fantastic way of getting your dynamic data to avoid page caching, as it’s swapped in with javascript.

So with that in mind, let’s add some data to the returned fragments.

add_filter( 'woocommerce_add_to_cart_fragments', 'iconic_cart_count_fragments', 10, 1 );

function iconic_cart_count_fragments( $fragments ) {
    
    $fragments['div.header-cart-count'] = '<div class="header-cart-count">' . WC()->cart->get_cart_contents_count() . '</div>';
    
    return $fragments;
    
}

We’re hooking into the fragments that are returned and adding our own. The $fragments variable is an array of data. Each item is a key/value pair. The key is an element target, which you can see we’ve set to div.header-cart-count; this is the element and class name of the code we added to our header. The value is the same content as we added to our header template, however, as this is being fetched after adding to cart, it will include anything we’ve just added.

Try It Out

That’s actually all there is to it. When the page loads or an item is added to the cart via AJAX, it will now be updated on the page. Important things to note:

  • The HTML element you define in the fragment key will be replaced. The content is not inserted into that element.
  • The fragments are cached, so if you change your fragment code, empty or modify the basket!
  • The fragments are also applied on/after page load, not only when an item is added to the cart.
  • You could replace any kind of content on the page when this is triggered.