Reputation: 475
I'm building an SPA using wordpress and woocommerce. Everything works fine (displaying products, handling payments, etc), except for emptying the user's cart after payment is complete. I wrote most endpoints custom.
In my payment handling endpoint, I wrote WC()->cart->empty_cart()
after successful payments. This seems to work when I check WC()->cart->get_cart
before and after emptying it (it's full before, empty after), however, when I subsequently open my cart modal (also using WC()->cart->get_cart()
, but via a GET request), the items are still in there. If I complete the checkout via the woocommerce standard checkout pages instead of the SPA the cart empties just fine.
I know there are some other questions on this forum regarding this issue, but none of the solutions work for me. I tried WC()->cart->empty_cart(true)
and setting 'cart' in the WC()->session
to an empty array. I don't really know where else the cart is stored, or how WC()->cart accesses this information, but I'm guessing it has to do with the fact that I'm trying to empty via an asynchronous request?
Upvotes: 1
Views: 2335
Reputation: 475
As it turns out, this problem only occurred for logged in users. There is a persistent cart for logged in users, that is supposed to be cleared when true
is passed into empty_cart
(default). However, since this request is made via API, the wordpress function get_current_user_id
that is used by empty_cart
returns 0 because it doesn't have access to the correct user global on the server. This can be solved by adding a wordpress nonce in the headers of the ajax request to make the user available to the server. When this nonce is supplied, the aforementioned function to clear the cart works just fine. More info about nonces: https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
Upvotes: 1
Reputation: 2744
PHP call too WC()->cart->empty_cart()
won't magically call the frontend work which is needed to refresh the HTML.
to update the HTML you would have to do something like
jQuery(document.body).trigger('wc_fragment_refresh');
Feel free to check wp-content/plugins/woocommerce/assets/js/frontend/cart-fragments.js
and see what it actually does.
Upvotes: 0