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!
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.
Let’s say you’ve added an element in your header that displays the total cart count, like so:
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
So with that in mind, let’s add some data to the returned 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.