I'm trying to implement a custom discount rule to the cart. Basically there is WooCommerce and the site is selling t-shirts. There is a current promotion that if you buy 3 t-shirts, you have to pay only for 2 and the one with the lowest price you get for free.
I created a custom function using the hook woocommerce_cart_calculate_fees
and so far it's working.
Here is my code:
add_action( 'woocommerce_cart_calculate_fees', 'iom_add_custom_discount', 10, 1 );
function iom_add_custom_discount( $wc_cart ){
$discount = 0;
$product_ids = array();
$item_prices = array();
$in_cart = true;
foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_product = $cart_item['data'];
if ( has_term( 'detski-bodita', 'product_cat', $cart_product->get_id() ) ) {
$in_cart = true;
}else {
$product_ids[] = $cart_product->get_id();
$item_prices[$cart_product->get_id()] = $cart_product->get_price();
}
}
if( $in_cart ) {
$count_ids = count($product_ids);
asort( $item_prices ); //Sort the prices from lowest to highest
$count = 0;
if( $count_ids == 3 ) {
foreach( $item_prices as $id => $price ) {
if( $count >= 1 ) {
break;
}
//$product = wc_get_product( $id );
//$price = $product->get_price();
$discount -= ($price * 100) / 100;
$count++;
}
}
}
if( $discount != 0 ){
$wc_cart->add_fee( 'Отстъпка', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
The discount is displayed and applied. But, it appears that it only works if I have 3 different products in the cart. If I have 1 product with quantity 2 and 1 product with quantity 1 it's not working.
How to tweak the function to make it work for item quantity count instead?
Edit :
Explanation about product categories in the discount:
The discount should only be applied if 3 items from the same category are in the cart.
For example, the categories are t-shirts and hoodies. If I have 3 t-shirts in my cart, the discount should be applied. If I have 2 t-shirts and 1 hoodie the discount should not be applied.