Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Cart and Pricing

Dynamic Pricing, Fees and Discounts

Change prices in WooCommerce safely: woocommerce_before_calculate_totals, product price filters, cart fees, tiered pricing, caching and rounding, with runnable stand-ins.

Almost every store eventually needs a price that is not simply "the number on the product": ten or more units get 5% off, wholesale customers pay a different amount, a handling fee appears for small orders. WooCommerce gives you three places to change money, and picking the right one decides whether your prices are correct, fast and cache-friendly. The three are the product price filters (change what a product reports as its price), the cart price hook (change the price of a line when the cart is calculated) and cart fees (add or subtract a separate line).

This lesson explains each, shows the patterns that avoid the classic bugs (a discount applied twice, a stale price in a cached page, a rounding cent that does not add up), and ends with runnable stand-ins. The real WooCommerce code is read-only here because it needs WordPress and WooCommerce. The stand-ins are plain PHP on the site's runner and work in integer cents, as described in Representing Money Correctly. For the business side of tiers and price lists, see Pricing Models.

Where prices can be changed

flowchart LR
    A["Product price in the database"] --> B["Product price filters<br/>(catalog, single product)"]
    A --> C["Cart item product object"]
    C --> D["woocommerce_before_calculate_totals<br/>(your line prices)"]
    D --> E["Cart totals engine"]
    F["woocommerce_cart_calculate_fees<br/>(your fees)"] --> E
    E --> G["Order totals"]

Product filters affect what shoppers browse; the cart hook and fees affect what they pay.

A simple rule: if the price should show on the shop page, the product page and in the cart, change it with the product filters. If it depends on the cart (quantity, who is logged in, what else is in the basket), use the cart hook or a fee.

Product price filters

Every WC_Product reads its price through a getter, and each getter runs a filter. The ones you will use most (read-only):

PHP
<?php
// Price used for buying and for sorting/displaying.
add_filter( 'woocommerce_product_get_price', 'acme_member_price', 20, 2 );
// Variations have their own filter name.
add_filter( 'woocommerce_product_variation_get_price', 'acme_member_price', 20, 2 );

function acme_member_price( $price, $product ) {
    if ( '' === $price || ! is_user_logged_in() ) {
        return $price;
    }

    // Member price is 10% off the regular price, stored as a string by WooCommerce.
    $regular = (float) $product->get_regular_price();

    return $regular > 0 ? wc_format_decimal( $regular * 0.9, wc_get_price_decimals() ) : $price;
}

Notes that matter in practice:

  • The filter receives $price as a string and expects a string (or number) back. An empty string means "no price"; keep it empty so the product stays unpurchasable.
  • Related filters exist for regular_price and sale_price, and woocommerce_product_is_on_sale controls the "Sale!" badge. If you change only the price and not the sale state, the strike-through price will not appear.
  • Variable products show a range ("$10 - $20") that is computed from all variations and cached in a transient. If your filter depends on the user or the session, the cached range will be wrong for some shoppers unless you vary the cache with the woocommerce_get_variation_prices_hash filter. See the caching section below.
  • woocommerce_get_price_html changes only the markup of the price, not the value the cart charges. Use it for display, such as "From $4.50".

Pricing in the cart: woocommerce_before_calculate_totals

Quantity-dependent prices cannot be known on the catalog page, so they are set while the cart is calculated. The hook receives the WC_Cart, and each cart item holds a product object whose price you can set for this request:

PHP
<?php
add_action( 'woocommerce_before_calculate_totals', 'acme_apply_tier_prices', 20 );

function acme_apply_tier_prices( WC_Cart $cart ): void {
    // Guard: skip the admin screens, but allow AJAX requests that update the cart.
    if ( is_admin() && ! wp_doing_ajax() ) {
        return;
    }

    foreach ( $cart->get_cart() as $cart_item ) {
        $product = $cart_item['data'];
        $base    = (float) $product->get_regular_price();
        $percent = acme_tier_percent( (int) $cart_item['quantity'] );

        // Always compute from a stable base, never from get_price().
        $product->set_price( $base * ( 100 - $percent ) / 100 );
    }
}

The line $base = $product->get_regular_price() is the important detail. This hook can run more than once in a single request (cart page, mini-cart fragments, checkout refreshes, the Store API). If you wrote $product->set_price( $product->get_price() * 0.95 ), the second run would discount the already discounted price and a 5% discount would silently become 9.75%. Compute from a value the hook does not change: the regular price, a price you stored in the cart item data when the item was added, or a sale price you read explicitly. Make the function idempotent: running it twice must give the same result as running it once.

Other points:

  • Use a late priority (20 or more) so other plugins that change base prices run first.
  • Do not save the product here. set_price() changes the in-memory object for this request; the database price stays as it was. That is exactly what you want.
  • The customer sees the new unit price in the cart and checkout, and the order line items store what was charged.
  • The hook runs for the block-based cart and checkout too, because the Store API recalculates the same cart.
  • Prices set this way do not show on the catalog page. If shoppers should see "Buy 10, save 5%" before adding to the cart, show it as text with a display hook (see Template Overrides and Plugin Templates for where to place it) or use the product price filters for the base case.

Cart fees

A fee is a separate line in the cart totals. Add it on woocommerce_cart_calculate_fees:

PHP
<?php
add_action( 'woocommerce_cart_calculate_fees', 'acme_small_order_fee' );

function acme_small_order_fee( WC_Cart $cart ): void {
    if ( is_admin() && ! wp_doing_ajax() ) {
        return;
    }

    $subtotal = (float) $cart->get_subtotal();   // before tax, after line-price changes

    if ( $subtotal > 0 && $subtotal < 25 ) {
        // name, amount, taxable?, tax class
        $cart->add_fee( __( 'Small order fee', 'acme' ), 3.00, true, '' );
    }
}

add_fee( $name, $amount, $taxable = false, $tax_class = '' ) adds one fee; a negative amount makes a discount line, which is a handy way to implement "5% off the whole order" when you do not want to touch line prices. Fees are recalculated each time, so they never need cleaning up, and the hook has the same "may run several times" behavior, which is safe because fees are rebuilt from scratch on each cart calculation.

Think about tax. A taxable fee gets tax added at the rate of the tax class you pass (an empty string means the standard class), which matters for accounting. A negative taxable fee reduces the taxable base; the rules for how this interacts with line discounts differ between jurisdictions, so check with your accountant before using negative fees for anything beyond simple cases. Tax details are in Taxes, Currency and Formatting.

Tiered and bulk pricing models

There are three common shapes, and the choice changes the math:

  1. Whole-quantity tier: once you buy 10, all 10 units cost 5% less. Simple and what most shoppers expect.
  2. Marginal (graduated) tier: the first 9 cost full price, units 10 to 24 cost 5% less, and so on, like income-tax brackets. Better for margin control, harder to explain.
  3. Fixed-price tiers: 1 unit is 10.00, 10 units cost 8.50 each. Easier to read in a table than percentages.

Whichever you choose, store the tier table as data (product meta or an option) rather than hard-coding it, validate that tiers are sorted and that discounts never push the price below your floor, and always read the price for the line's total quantity of that product, not the number of separate lines (a shopper can add the same product twice with different cart item data).

Caching and display

Dynamic prices fight with caches:

  • Page caches (a plugin or a CDN) store the HTML of product pages. Any price that varies by user or session must not be printed into cached HTML. Either keep the cached page generic (the catalog shows the normal price) or load personalized prices with JavaScript from an uncached request.
  • Cart and checkout pages are normally excluded from page caches, which is why changes in the cart hook are safe.
  • Variation price transients are shared by all visitors. If the member price changes the variation range, add the user group to the hash with woocommerce_get_variation_prices_hash, or the first visitor decides what everyone sees.
  • Product filters run a lot: on a category page with 60 products, your filter runs at least 60 times. Do not run a database query in it; read from the product object or a pre-loaded array.

Rounding

WooCommerce stores prices as decimal strings and rounds to the store's number of decimals (wc_get_price_decimals()) when it formats and totals. Float math such as 19.99 * 0.95 produces numbers with a long tail, and then rounding at different steps (per unit, per line, per order) can differ by a cent. Pick one rule and apply it the same way everywhere. The reliable approach is the one from the fundamentals lesson: work in integer minor units, round once and in a documented direction, and compare totals in tests. The stand-in below does exactly that. For discount stacking rules in general, see Building a Promotions Engine.

Runnable stand-ins

These examples are not WordPress: there is no cart object or hook system here. They reproduce the logic of a tiered price rule and an idempotent repricing hook in plain PHP so you can see the numbers.

PHP Tier table in integer cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that every number is an integer until the moment it is printed. The line total is the rounded unit price times the quantity, which is also how WooCommerce displays a unit price and a line subtotal in the cart.

The second stand-in shows why the cart hook must be idempotent, and how a fee is rebuilt on every calculation.

PHP Running a cart hook twice, safely and unsafely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the first two rows the unsafe version gives 1.90 once, then drifts to 1.72 after three runs, while the safe version stays at 1.90 however often the hook runs. The last row shows the fee appearing because the subtotal is under 25.00.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which hook should you use to set a line price that depends on the cart quantity?

    The quantity is only known in the cart, so the line price is set while the cart is calculated. The product filters run on the catalog, where there is no quantity, and the price HTML filter only changes markup.
  2. 2. Why should a woocommerce_before_calculate_totals callback compute from the regular price instead of get_price()?

    Cart calculation is triggered by many requests and fragments, so your callback must be idempotent. Starting from a stable base gives the same answer each run.
  3. 3. What does $cart->add_fee( 'Gift wrap', 4.00, true ) do?

    A fee is a separate totals line. The third argument marks it as taxable, and fees are recalculated every time, so they need no cleanup.
  4. 4. Why can a user-specific price in a product price filter be wrong for some visitors?

    The price range of a variable product is stored in a transient shared by all visitors, so the first visitor's price can leak to others unless the cache hash includes the differentiating factor.

Summary

  • Change what a product reports with the product price filters, what a cart line costs with woocommerce_before_calculate_totals, and extra charges or discounts with add_fee().
  • Cart hooks run many times per request: compute from a stable base so the callback is idempotent, and never save the product.
  • Fees are rebuilt on every calculation; mark them taxable with a tax class on purpose.
  • Do not print user-specific prices into cached HTML, and vary the variation price hash when prices differ by user.
  • Work in integer minor units and round once with a documented rule, so tiers, fees and totals agree to the cent.
  • The stand-ins show the logic only; the hooks need a real WooCommerce install.

Next: Coupons in Code