WooCommerce Tutorials

Update Custom Cart Count (or any HTML) after AJAX Add to Cart in WooCommerce

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.
Avatar

James is the founder of Iconic and an experienced WooCommerce plugin developer. He has been featured on numerous WordPress publications.

He is a keen photographer and currently shoots using his favourite mirrorless camera, a Fuji X-T20.

29 Responses

Avatar
Stephen Gunn 12 months ago

This article helped me solve a problem in 10 minutes that I thought would take a couple hours. Thanks.

Avatar
hitesh suhagiya 1 year ago

thank for this post it work perfectly
i how can i update drop down cart item-list ?

Avatar
Patricia Birchenough 1 year ago

Hi, I added the suggested code to the child theme's functions.php file, cleared all caches, and I don't see any change. I am having a problem with the mini cart icon not accurately displaying the item count unless the page is refreshed. Any additional help you can give would be appreciated. I am troubleshooting in a development environment, but the issue exists in the live site. Thanks in advance!

Avatar

Hi, i want to update mini cart when quantity is changed. How would i do that without a plugin

Avatar
Jhimross Olinares 1 year ago

Hi Tariq,

Do you mean that you want to change the icon when items added in the cart?

Avatar
Pierre-Léon 2 years ago

Wow!I've searched for hours and I had to ask on a Facebook group then someone sent me here and that was exactly what I needed. Thank you!

Avatar
Elliot Alderson 2 years ago

Hi,
Great blog, You have summed up all the points very efficiently. Thank you for sharing.
Thanks

Avatar
Jairam Swami 2 years ago

Is this possible to update the cart count when any product removed from cart like this with ajax? If possible then please help to get this.

Avatar

Hi, have you got your answer, i have same question

Avatar
Mauro Iman 3 years ago

Just wanted to say that, after hours of search and lot of pages with no clear answers, I stumble upon yours, which really helped me to make progress with a custom cart I'm coding. Sinceraly, thanks!

Avatar
Myles Hyson 3 years ago

How would you go about doing this when you remove a product from the cart?

Avatar

Great Article! I'm having some trouble executing some javascript code off the back of this function. Essentially IF number of items in cart (AJAX) is equal to 5...trigger a javascript alert. Is this possible? My code is below...

add_filter( 'woocommerce_add_to_cart_fragments', 'wc_mini_cart_refresh_number');
function wc_mini_cart_refresh_number($fragments){
ob_start();
?>

cart->get_cart_contents_count(); ?>

5) {

//Javascript alert
?>

(function($){
$('body').on( 'added_to_cart', function(){
// Testing output on browser JS console
console.log('added_to_cart');
// Your code goes here
swal(
'You added all the items!',
'Proceed to checkout?',
'success')
});
})(jQuery);

<?php
}
}

Avatar
James Kemp admin 3 years ago

If I understand correctly, you're trying to return this JS with the fragments? If so, you shouldn't! You can add the JS to a global JS file and it'll be triggered when 'added_to_cart' is triggered. You should change it to `$( document.body ).on( 'added_to_cart', function() {} );`

Avatar

Thanks for the reply James! - I'm trying to return the JS if the number of items in the cart == 5...I assumed fragments would hold the number of items in the cart which I could pass into the IF condition?

The JS trigger actually works and displays the alert once an item is added to the cart when I use an IF statement such as IF (is_page('leanshop') { *Execute JS*)

Where I am having difficulty is applying the IF Logic to only throw the JS alert if the number of items in the cart == 5. Because my shop archive page is using AJAX, I believe it's not getting the count of items in the cart successfully.

Are you saying to move my IF statement and put in the {} where the added_to_cart is triggered, as per your comment above?

Avatar
Ali Boozarpoor 3 years ago

hi
Thanks for your article,
i create a mini cart using this technic , number of item and total price update with ajax but new product (title-link-thumbnail ) appear when page reload.
how can i show new product to mini cart without refresh page (when someone add new product to his cart)?

Avatar
abdo arbab 3 years ago

That's an impressive functionality. Thanks for sharing that with us, you saved me a lot of time.

Avatar

Hi, great it works perfectly for my cart items count!

I have a minicart too. How would you go about updating the minicart with the same technique?

How would I trigger animation, like add-remove a class with js?

Thanks for your help!

Avatar
simon codrington 3 years ago

Thanks for the article mate. This was exactly what I needed and worked perfectly, cheers!

Avatar
Samuel Gadea 4 years ago

Hello, is it possible to hide the div when the product quantity is equal to 0 ?

Avatar
James Kemp admin 4 years ago

Hey,

When you return the HTML just add a class to it that you set as display: none

Avatar
alessandro cane' 2 years ago

can you please explain exactly how you check if empty? i've tryed putting anf if/else condition but it doesn't work :-(

add_filter( 'woocommerce_add_to_cart_fragments', 'iconic_cart_count_fragments', 10, 1 );
function iconic_cart_count_fragments( $fragments ) {
if ( WC()->cart->get_cart_contents_count() !== 0 ) {
$fragments['span#conteggio'] = '' . WC()->cart->get_cart_contents_count() . '';
return $fragments;
} else {
$fragments['span#conteggio'] = '';
return $fragments;
}
}

Avatar
Artur Bobinski 2 years ago

You can do so by doing the following;

$cart_count = WC()->cart->get_cart_contents_count();
if ( $cart_count !== 0 ) {
put your stuff here;
}

or similar to that but that would check it correctly.

Hope it helps!

Leave a Reply

Your email address will not be published. Required fields are marked *