I would like to have a volume discount for only one of my woocommerce products. I found the code below, but it applies to all products. How can I convert this code so that it is only valid for a specific product (based on product ID or product SKU)?
In addition, I would like the discount price to appear on the product page based on the specified quantity.
add_action( 'woocommerce_before_calculate_totals', 'quantity_based_pricing', 9999 );
function quantity_based_pricing( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Define discount rules and thresholds
$threshold1 = 2; // Change price if items > 2
$discount1 = 20; // Reduce unit price by 20$
$threshold2 = 3; // Change price if items > 3
$discount2 = 40; // Reduce unit price by 40$
$threshold3 = 4; // Change price if items > 4
$discount3 = 60; // Reduce unit price by 60$
$threshold4 = 5; // Change price if items > 5
$discount4 = 80; // Reduce unit price by 80$
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 ) {
$price = round( $cart_item['data']->get_price() - ( $discount1 ), 2 );
$cart_item['data']->set_price( $price );
} elseif ( $cart_item['quantity'] >= $threshold2 ) {
$price = round( $cart_item['data']->get_price() - ( $discount2 ), 2 );
$cart_item['data']->set_price( $price );
}
elseif ( $cart_item['quantity'] >= $threshold3 ) {
$price = round( $cart_item['data']->get_price() - ( $discount3 ), 2 );
$cart_item['data']->set_price( $price );
}
elseif ( $cart_item['quantity'] >= $threshold4 ) {
$price = round( $cart_item['data']->get_price() - ( $discount4 ), 2 );
$cart_item['data']->set_price( $price );
}
}
}