Dynamic Pricing in WooCommerce Using Custom PHP Code – A Complete Guide
🧩 Introduction
WooCommerce is a powerful eCommerce platform, but sometimes store owners need advanced pricing strategies that go beyond what plugins offer. This is where custom PHP code becomes useful.
In this article, you’ll learn how to implement dynamic pricing in WooCommerce using PHP – no third-party plugin required.
What is Dynamic Pricing?
Dynamic pricing allows product prices to change automatically based on rules like:
- Quantity purchased (bulk discount)
- User role (wholesale vs retail)
- Date/time-based offers (limited time pricing)
- Cart conditions (BOGO, total value discount)
Example Use Case
Let’s implement a simple quantity-based discount:
- Buy 1–4 items → Regular price
- Buy 5 or more → 20% discount
PHP Code for Dynamic Pricing
Add the following code to your theme’s functions.php
file or a custom plugin:
add_action('woocommerce_before_calculate_totals', 'custom_dynamic_pricing_based_on_quantity', 20, 1);
function custom_dynamic_pricing_based_on_quantity($cart) {
if (is_admin() && !defined('DOING_AJAX')) return;
// Loop through cart items
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
// Set original price
$original_price = $product->get_regular_price();
// Check quantity and apply 20% discount
$discounted_price = $original_price * discount_rate(); // 20% off
$product->set_price($discounted_price);
}
}
Conclusion
Dynamic pricing using PHP gives you complete control over your WooCommerce store’s pricing logic. Whether you need quantity-based discounts, user-role pricing, or date-based sales, this approach helps avoid bloated plugins and keeps performance optimized.