'WooCommerce - Empty the current cart on add-to-cart event
So I'm selling a digital product with WooCommerce but I don't have a shop page or anything, I just have a big CTA button on my landing page which adds the given product ID to the cart and proceeds to the checkout page upon click.
But let's say the user wants to go back to the landing page to double-check something and complete the checkout process then the product quantity becomes 2 and they can't edit the cart because I've removed all of the shop pages except for the checkout.
So I need to write a hook/filter function that tells WC to empty the current cart before adding the new product to the cart but I also have this upsell plugin that promotes my upsell products on the checkout submit event, right before the payment is charged.
As you can see, I need to check the product ID so my function wouldn't empty the cart if it's an Upsell product, which would be something like the example below, in pseudo-code;
add_filter('woocommerce_add_to_cart_validation', function(...$filterArgs){
(int) $productID; // ID of the product being added to cart
(int) $upsellProductID; // ID of the Upsell product
(bool) $isCartEmpty; // check if the current cart is empty or not
if($productID !== $upsellProductID && $isCartEmpty) {
emptyCartFunctionOfWooCommerce();
return $cartVariableFromFilterArgs
}
});
I'm not fluent in WP hooks yet so do you have any idea how can I do this? Thank you so much.
EDIT: I just did it without ID checking and it didn't interfere with the Upsell function. If anyone has the same issue, you can use something like the code below.
// This will empty the current cart before adding the product to the cart.
add_filter( 'woocommerce_add_to_cart_validation', function($passed, $product_id, $quantity){
if (!WC()->cart->is_empty()) {
WC()->cart->empty_cart();
}
return $passed;
}, 20, 3 );
Solution 1:[1]
Edit the product, go to Inventory, and select "Sold individually" "Enable this to only allow one of this item to be bought in a single order". This will stop customers adding more than 1 of that product to the cart.
Once you have done this, change your button to an <a>
tag.
<a href="yourdomain.com/cart/?add-to-cart=35407">Buy Now</a>
This should take you to the cart page and add the product to your cart, but limit it to 1.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |