Hey guys :) 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:
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', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
Here is a screenshot of the cart page --> https://pasteboard.co/JkES3RD.png The discount is displayed and applied. The tricky part I can't get to is, how to make the price of the discounted product striked and display price 0.00 in the table and how to edit the function so in the mini cart still displays 3 products, but to show the discounted price of 2 products? Thanks so much in advance! :)
EDIT: Also, 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?