I’m using the following code to add a free product to the basket when over a certain cart total.
When I drop below the cart total it hits the if statement but won’t remove the product.
I think this may be because the quantity is set to 1 on the basket form and my code isn’t overriding that quantity to set it to 0 (and remove it).
Is there another way to remove it or override it?
/*
* Automatically adding the product to the cart when cart total amount reach to £20.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 20;
$free_product_id = 85028; // Product Id of the free product which will get added to cart
if ( $woocommerce->cart->total >= $cart_total ) {
echo "Over the limit";
$quantity = 1;
WC()->cart->add_to_cart( $free_product_id, $quantity );
} elseif($woocommerce->cart->total < $cart_total) {
echo "Under the limit";
$quantity = 0;
WC()->cart->remove_cart_item( $free_product_id, $quantity );
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
I’ve tried using this question but cannot get it to work, it won’t even add the item to my basket.
I’m using Woocommerce version 3.6.5 if that helps.
2
Answers
I’m not sure on how Woocommerce works but I assume the remove_cart_item ‘quantity’ parameter takes the amount of the item to remove from the basket. So set the value of $quantity to 1 and it should remove one of the free product from the basket. If there happens to be more than one free item in the basket then you’ll need to set your $quantity value accordingly.
Furthermore, you are adding a free item every time a product is added when the basket value is higher than $cart_total. Maybe add a check to see if it already exists in the basket before adding it?
Hope I understood your question correctly