I use a code that adds a free product to the cart if the total is equal to or greater than 1500. If the total is less than 1500, then the product is removed.
add_action( 'woocommerce_before_calculate_totals', 'add_free_product_to_cart' );
function add_free_product_to_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$minimum_amount = 1500;
$free_product_id = 290;
// Initializing
$cart_subtotal = 0;
$cart_items = $cart->get_cart();
// Loop through cart items (first loop)
foreach ( $cart_items as $cart_item_key => $cart_item ){
// When free productis is cart
if ( $cart_item['data']->get_id() == $free_product_id ) {
$free_item_key = $cart_item_key; // Free product found (get its cart item key)
$cart_item['data']->set_price(0);
}
// Get cart subtotal incl. tax and discounts (excluding free product)
else {
$cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
}
}
// When cart total is up to the minimum amount, add the free product if not already there
if ( $cart_subtotal >= $minimum_amount && ! isset($free_item_key) ) {
$cart_item_key = $cart->add_to_cart( $free_product_id );
// display notice after removal
wc_add_notice( __("Thank you! Here's your free product."), 'notice' );
}
// if below the minimum, remove the free product
elseif ( $cart_subtotal < $minimum_amount && isset( $free_item_key ) ) {
$cart->remove_cart_item( $free_item_key );
// display notice after removal
wc_add_notice( sprintf(
__("Your cart subtotal is less than %s and therefore, the free product was removed."), wc_price($cart_subtotal)
), 'notice' );
}
}
The code works, just one problem. When this product is added to cart by a customer, this product is not added.
How can I make this product be added to cart and if the amount is 1500 or more, then the second free product is added to the first product?
I’ll be glad you helped!