I’m building a small Woocommerce site using Sage11 and needed to just call WC()→cart→get_cart_contents_count() on page load to update a little basket icon with the number of items in the cart - seems simple enough!
However after a lot of head scratching and cussing I discover that the REST API does not have access to the WC()→cart - apparently because of ‘performance issues’ as per this github ticket https://github.com/woocommerce/woocommerce/issues/23800
There is a convoluted work around, but I couldn’t get it to work.
So given that I need access to WC()→cart to do this, does the conventional wisdom of using the REST API fall down here? I know the old way works, but if there’s a better approach I’d be grateful to hear it.
I think adding a data attribute like <icon-element data-cart-item-count=”{{ $cartItemCount }}”></icon-element> and then styling an ::after psuedo element with content: attr(data-cart-item-count) removes the need of JS entirely.
You would only add the ::after psuedo element if the icon has a specific class which is added if the item count is greater than 0. The class would be conditionally added using the laravel blade @class directive. And the $cartItemCount variable would be defined in a view composer like app/View/Composers/App.php.
Hope this fits within the context of your project!
Yeah I thought about that approach, the main reason for not doing that is that in this case I’m building out a kind of search results page, so the visitor can click a link for a product and go off to the Single Product page, add the item to their basket and then use the Browser back button to return to the results page - in this case, the browser ‘remembers’ the value of the cart count from the first visit and does not show correct number of items. With a small ajax call on page load, even going back in history will manifest the correct readout
Yeah that’s it @ben - did try /wp-json/wc/store/v1/cart but I was passing in the same header as for the REST API with the key and the secret, removing that worked! As it says in the docs:
In contrast to the WooCommerce REST API, the Store API is unauthenticated and does not provide access to sensitive store data or other customer information.