How can I apply a discount in products cart for product that costs less?
For example:
I have two product in cart: one cost 150$ and one 200$. I would like to apply a 10 percent discount only for product that cost less, in this case the first one.
I have this code but it works only for the second product in cart:
add_filter( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialising
$count = 0;
$discount = 0.10; // 10 %
$discounted = 0;
// Iterating though each cart items
foreach ( $cart_object->get_cart() as $cart_item ) {
$count++;
if( 2 == $count){ // Second item only
$price = $cart_item['data']->get_price(); // product price
$discounted_price = $price - ($price * $discount); // calculation
$discounted = $price - $discounted_price;
// Set the new price
//$cart_item['data']->set_price( $discounted_price );
break; // stop the loop
}
}
$cart_object->add_fee( "Discount (10%) on second product", -$discounted, true );
}