I want to add a 30% discount on the cheapest item in the cart, except if it already has a discount.
Based on Cart discount for product that cost less in Woocommerce answer code, this is my code attempt:
add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
function discount_on_cheapest_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only for 2 items or more
if ( $cart->get_cart_contents_count() < 2 ) return;
// Initialising
$percentage = 50; // 10 %
$discount = 0;
$item_prices = array();
// Loop though each cart items and set prices in an array
foreach ( $cart->get_cart() as $cart_item ) {
$product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
}
sort($product_prices_excl_tax);
if( ! $cart_item['data']->is_on_sale() ){
$discount = reset($product_prices_excl_tax) * $percentage / 100;
$cart->add_fee( "Discount on cheapest (".$percentage."%)", -$discount );
}
}
Is there a way to make it work so if the product with the lowest price is not on sale, then apply a 30%, if it is on sale, don't. But this applies only to the lowest, if any other product is on sale, we skip it.