69
You’re looking to assign different unit prices based on the quantity added to Cart, for example from 1-100 price is $5, from 101-1000 price is $4.90 and from 1001 units ordered price becomes $4.75.
There are many “Dynamic Pricing” plugins out there (and the number #2 on this article would suit complex pricing rules and dynamic discounts), but this time I want to teach you a simple code to DIY WooCommerce quantity-based pricing.
As usual, comments and shares are much appreciated. Enjoy!
PHP Snippet: Change Product Price Based on Quantity Added to Cart (Bulk Pricing)
In our example, our product price is €34 and I want to apply a 5% discount above 100 units and a 10% discount above 1000 units. Screenshots for threshold 1 and threshold 2 are below the snippet.
/**
* @snippet Bulk (Dynamic) Pricing - WooCommerce
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 3.8
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_before_calculate_totals', 'tutoraspire_quantity_based_pricing', 9999 );
function tutoraspire_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 = 101; // Change price if items > 100
$discount1 = 0.05; // Reduce unit price by 5%
$threshold2 = 1001; // Change price if items > 1000
$discount2 = 0.1; // Reduce unit price by 10%
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] 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 );
}
}
}