Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. <?php
  2. /**
  3. * Hook: Empty cart before adding a new product to cart WITHOUT throwing woocommerce_cart_is_empty
  4. */
  5. add_action ('woocommerce_add_to_cart', 'lenura_empty_cart_before_add', 0);
  6.  
  7. function lenura_empty_cart_before_add() {
  8. global $woocommerce;
  9.  
  10. // Get 'product_id' and 'quantity' for the current woocommerce_add_to_cart operation
  11. if (isset($_GET["add-to-cart"])) {
  12. $prodId = (int)$_GET["add-to-cart"];
  13. } else if (isset($_POST["add-to-cart"])) {
  14. $prodId = (int)$_POST["add-to-cart"];
  15. } else {
  16. $prodId = null;
  17. }
  18. if (isset($_GET["quantity"])) {
  19. $prodQty = (int)$_GET["quantity"] ;
  20. } else if (isset($_POST["quantity"])) {
  21. $prodQty = (int)$_POST["quantity"];
  22. } else {
  23. $prodQty = 1;
  24. }
  25.  
  26. error_log('prodID: ' . $prodId); // FIXME
  27. error_log('prodQty: ' . $prodQty); // FIXME
  28.  
  29. // If cart is empty
  30. if ($woocommerce->cart->get_cart_contents_count() == 0) {
  31.  
  32. // Simply add the product (nothing to do here)
  33.  
  34. // If cart is NOT empty
  35. } else {
  36.  
  37. $cartQty = $woocommerce->cart->get_cart_item_quantities();
  38. $cartItems = $woocommerce->cart->cart_contents;
  39.  
  40. // Check if desired product is in cart already
  41. if (array_key_exists($prodId,$cartQty)) {
  42.  
  43. // Then first adjust its quantity
  44. foreach ($cartItems as $k => $v) {
  45. if ($cartItems[$k]['product_id'] == $prodId) {
  46. $woocommerce->cart->set_quantity($k,$prodQty);
  47. }
  48. }
  49.  
  50. // And only after that, set other products to zero quantity
  51. foreach ($cartItems as $k => $v) {
  52. if ($cartItems[$k]['product_id'] != $prodId) {
  53. $woocommerce->cart->set_quantity($k,'0');
  54. }
  55. }
  56. }
  57.  
  58. }
  59.  
  60. }
  61. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement