Stuck WooCommerce Cart Counter: Clear Cache After Add To Cart

Do you have a counter on your WooCommerce site that shows the user how many items are in their cart? We do, it looks like this on every page:

cart-counter-woocommerce

We do this with a very simple line of code in the header.php file of our theme:

CART | <?php echo sizeof( WC()->cart->get_cart() ); ?>

This gets a count of items in the cart array.  It is very simple, clean and efficient, unless you having a caching plugin installed.  If you do, then on pages that are fully cached the cart number will not be regenerated until the cache is cleared.

Clear Cache Dynamically

I use Comet Cache on our site.  It’s a killer caching plugin and the free version has so many features out of the box it’s incredibly useful.  So how do we clear this number? Simple.

In our functions.php file we hook into the woocommerce_add_to_cart and simply clear the cache using the object comet_cache‘s built in clear() method.  If you are using a popular, modern caching plugin it probably has a function that works very similar to this and you can call it here as well.

https://gist.github.com/ChrisFlannagan/003d3efa9cb2aec88b0e54b654e20c77

Leave a Reply

Your email address will not be published.