I have three products that I want to give as a free item. If anyone adds more quantity from an item I want to give only one quantity as free. That means deducting price of one quantity from the subtotal. For example: the price of a product is 4 and the total quantity added is 5. So the total subtotal will be 20. Now, I want to deduct the price of one quantity from the subtotal. So, the final outcome will be subtotal 15, after deducting the price.
I have tried this code.
$free_items_id = [344,345,346];
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( in_array( $cart_item['product_id'], $free_items_id ) ) {
if ( $cart_item['quantity'] > 1 ) {
$price_to_be_deducted = $cart_item['data']->get_price();
$updated_price = ( $cart_item['quantity'] - 1 ) * $price_to_be_deducted;
$cart_item['data']->set_price( $updated_price );
break;
}
else {
$cart_item['data']->set_price( 0 );
}
}
}
But this code multiplies the $updated_price with the total quantity number of the product. Can anyone give any solution.