Reputation: 71
Now I have the following Woocommerce discount: 1) at one item --> 10% only for not in sale items 2) at two items 20% for the cheapest item including on sale items
I tried use Cart discount based on cart item count and only for items that are not in sale and Cart discount for product that cost less in Woocommerce answers code.
How can I add 10% discount, when I have two items, to the second item?
How can add discount only for not in sale items when I have two items, to the second item?
Upvotes: 1
Views: 553
Reputation: 253901
The following will make a 10% discount on the 2nd item when there is not items on sale in cart:
add_action('woocommerce_cart_calculate_fees' , 'custom_2nd_item_discount', 10, 1);
function custom_2nd_item_discount( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only for 2 items or more
if ( $cart->get_cart_contents_count() < 2 )
return;
// Initialising variable
$has_on_sale = false;
$count_items = $discount = 0;
$percentage = 10; // 10 %
// Iterating through each item in cart
foreach( $cart->get_cart() as $cart_item ){
$count_items++;
if( $cart_item['data']->is_on_sale() ){
$has_on_sale = true;
}
if( 2 == $count_items ){
$discount = wc_get_price_excluding_tax( $cart_item['data'] ) * $percentage / 100;
}
}
// Apply discount to 2nd item for non on sale items in cart
if( ! $has_on_sale && $discount > 0 )
$cart->add_fee( sprintf( __("2nd item %s%% Discount"), $percentage), -$discount );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Upvotes: 1