Hy,
I want to create a discount rule for WooCommerce with 50% discount on fourth product (the cheapest one). So if I have at least 4 products in my cart, I want to have a 50% off on the one with the lowest price. I tried various plugins, but I couldn't do this with any of them. Can someone help me?
Thank's in advance!
I tried various plugins, but I couldn't do this with any of them.
You can alter the product price in the Cart/Checkout with the woocommerce_before_calculate_totals hook.
Here I have an example for applying a discount for bulk quantities, so let me try to edit it for your custom task:
add_action( 'woocommerce_before_calculate_totals', 'bbloomer_fourth_item_half_off', 9999 );
function bbloomer_fourth_item_half_off( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
if ( count( $cart->get_cart() ) < 4 ) return; // AT LEAST 4 PRODUCTS
$min = PHP_FLOAT_MAX;
$cheapest = '';
// FIND CHEAPEST ITEM
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['data']->get_price() < $min ) {
$min = $cart_item['data']->get_price();
$cheapest = $cart_item_key;
}
}
// REDUCE CHEAPEST ITEM PRICE BY 50%
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cheapest == $cart_item_key ) {
$price = $cart_item['data']->get_price() / 2;
$cart_item['data']->set_price( $price );
}
}
}