Reputation: 97
Working on a WP Woocommerce,
If I add an item using https://url/?add-to-cart=1561&quantity=4 I see the item in every cart in every other session on the site, regardless if I was logged in or not.
For example: I add the item in browser (not logged in) and I see the product on another browser.
I've tried,
All result in a 'globally shared' cart across everyone visiting the site.
Any help or suggestions would be appreciated.
Upvotes: 0
Views: 2791
Reputation: 97
I hacked together a solution that has seemed to solve my issues.
It looks like my WC session was always setting a unique customer ID, the issue had something to do with the cart itself being used for multiple customer IDs.
My solution:
I set a session variable with a key of the customer id then assign all cart items to the variable.
$id = WC()->session->get_customer_id();
WC()->session->set($id, $my_cart);
Every time the cart has an item added to it, ( Ex: /?add-to-cart=1561 ) I added that item to the $my_cart variable via action hook.
function add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {}
add_action('woocommerce_add_to_cart', 'add_to_cart', 10, 6);
I essentially wrote my own functions to add/remove/update $my_cart which hooked into the woocommerce action hooks.
Action Hooks Used:
add_action('woocommerce_add_to_cart', 'add_to_cart', 10, 6);
add_action('woocommerce_remove_cart_item', 'remove_from_cart', 10, 1);
add_action('woocommerce_after_cart_item_quantity_update', 'update_cart', 10, 3);
Then on the cart page I added all the items from $my_cart to the 'official' woocommerce cart (making sure not to 're add' them to $my_cart) to get my desired result.
Closing:
Again, not exactly sure what issues caused this cart bug in the first place (my last thoughts were some sort of caching on the hosting platform) but this might be a good example for anyone who wants to store particular data in a woocommerce session via action hooks.
Upvotes: 1