I want to create a function to create conditional bulk dynamic pricing for WooCommerce, different unit prices based on the quantity added to cart.
I have two product tags ids (326, 327) and there is a bunch of product in each tag. I want to give a different discount for both tags and for the same quantity.
- Tag ID 326
- 15% discount above 10 units
- 20% discount above 25 units
- Tag ID 327
- 20% discount above 10 units
- 35% discount above 25 units.
This is the code I am working with:
add_action( 'woocommerce_before_calculate_totals', 'woocommerce_quantity_based_pricing', 9999 );
function woocommerce_quantity_based_pricing( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
if( has_term( 326, 'product_tag' ) ) {
$threshold1 = 10;
$discount1 = 0.15;
$threshold2 = 25;
$discount2 = 0.3;
} elseif( has_term( 327, 'product_tag' ) ) {
$threshold1 = 10;
$discount1 = 0.2;
$threshold2 = 25;
$discount2 = 0.35;
}
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() * ( 1 - $discount1 ), 2 );
$cart_item['data']->set_price( $price );
} elseif ( $cart_item['quantity'] >= $threshold2 ) {
$price = round( $cart_item['data']->get_price() * ( 1 - $discount2 ), 2 );
$cart_item['data']->set_price( $price );
}
}
}
Unfortunately without the desired result. Any advice?
