Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Real-World Projects

Project: Bulk Discount Extension

Build a WooCommerce bulk discount extension: tier meta on products, cart price calculation, price table display, coupon interplay and tests, with a runnable pricing engine.

In this project you put several earlier lessons together into one small, realistic extension: "buy more, pay less per unit". The shop owner defines tiers on each product (for example 10 or more units get 5% off, 50 or more get 12% off), shoppers see a price table on the product page, and the cart applies the right unit price automatically. We also decide how the tiers interact with coupons, because that is where most bugs hide.

The plugin code is read-only here, since it needs WordPress and WooCommerce. The heart of the extension, the pricing engine, is written as plain PHP with no WordPress calls, so you can run it, test it and later paste it into the plugin unchanged. That separation is the main design lesson of the project. Background reading: Dynamic Pricing, Fees and Discounts, Custom Product Fields and Tabs and Coupons in Code.

Plan and structure

TEXT
acme-bulk/
  acme-bulk.php              bootstrap, compatibility declaration
  includes/
    class-tier-table.php     pure PHP: validates and looks up tiers
    class-pricing.php        pure PHP: unit price for a quantity
    class-admin.php          product data panel and saving
    class-cart.php           cart price hook
    class-display.php        price table and cart display
  tests/
flowchart LR
    A["Product meta<br/>_acme_tiers"] --> B["Tier_Table<br/>(parse + validate)"]
    B --> C["Pricing<br/>unit price for qty"]
    C --> D["Cart hook<br/>set_price()"]
    C --> E["Product page<br/>price table"]
    D --> F["Coupons<br/>apply afterwards"]

Only the edges (meta, cart, display) touch WordPress; the middle is plain PHP.

Decisions we make up front:

  • Money in integer cents inside the engine (see Representing Money Correctly); convert at the edges only.
  • Tiers apply per cart line by quantity of that line. Aggregating all variations of one variable product is a common extension; we mention it at the end.
  • Percent tiers only. A fixed price per tier is a small change in Pricing.
  • Coupons apply after tiers, on the already reduced price. That is WooCommerce's natural order, and we document it instead of fighting it.

Step 1: the admin UI

Store tiers as one JSON string in product meta. That keeps one meta row per product and a simple, versionable format:

PHP
<?php
add_action( 'woocommerce_product_options_pricing', function () {
    woocommerce_wp_textarea_input( [
        'id'          => '_acme_tiers',
        'label'       => __( 'Bulk tiers', 'acme-bulk' ),
        'description' => __( 'One tier per line: minimum quantity, percent off. Example: 10,5', 'acme-bulk' ),
        'desc_tip'    => true,
    ] );
} );

add_action( 'woocommerce_admin_process_product_object', function ( WC_Product $product ) {
    // Nonce and capability are already checked by WooCommerce when saving a product.
    $raw = isset( $_POST['_acme_tiers'] ) ? wp_unslash( $_POST['_acme_tiers'] ) : '';
    $table = Acme_Tier_Table::from_text( is_string( $raw ) ? $raw : '' );

    $product->update_meta_data( '_acme_tiers', wp_json_encode( $table->to_array() ) );
} );

The text goes through the same parser that the runtime uses, so what is saved is always valid, sorted and de-duplicated. The woocommerce_admin_process_product_object hook hands you the product object, so you use the CRUD update_meta_data() and let WooCommerce save once (see CRUD Classes and Data Stores). Never trust the posted text: from_text() casts every number to an integer and drops anything that does not parse.

Step 2: the pricing engine (runnable)

This is the part worth testing hard. It validates a tier list, finds the best tier for a quantity, computes the unit price in cents, and also does the coupon step so we can study the interplay.

PHP Bulk pricing engine 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.

Look at what the parser rejects: the word abc, the quantity 1, and the 95 percent tier are all dropped, and the duplicate 10 keeps its last value (7). Rounding happens once per unit price, so the displayed unit price multiplied by quantity equals the line total, a property shoppers notice when it fails.

Step 3: the cart hook

The classic place to change prices is woocommerce_before_calculate_totals. It runs often, so the code must be idempotent: setting the price from the stored base price, never from the current (possibly already discounted) price.

PHP
<?php
add_action( 'woocommerce_before_calculate_totals', function ( WC_Cart $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    foreach ( $cart->get_cart() as $item ) {
        $product = $item['data'];
        $table   = Acme_Tier_Table::from_json( (string) $product->get_meta( '_acme_tiers' ) );
        if ( ! $table->has_tiers() ) {
            continue;
        }

        $fresh      = wc_get_product( $product->get_id() );   // untouched catalog object
        $base_cents = (int) round( (float) $fresh->get_price() * 100 );
        $unit_cents = Acme_Pricing::unit_cents( $base_cents, $table, (int) $item['quantity'] );

        $product->set_price( $unit_cents / 100 );
    }
}, 20 );

Important details:

  • Where does the base price come from? The product object inside a cart item is modified by set_price(), so reading its price again on the next run would discount twice. Loading a fresh object with wc_get_product() gives the catalog price every time (WooCommerce caches the data, so this is cheap). If another plugin also changes prices, agree on priorities.
  • Taxes. The example sets the price the way the store enters it. With prices entered including tax, discounting the displayed price and letting WooCommerce extract the tax is the simplest correct path; see Taxes, Currency and Formatting before you change it.
  • Sale prices. Decide whether tiers stack with a sale price. A common, safe rule: the tier discount applies to the active price, and the admin can disable tiers for products on sale. Whatever you choose, test it.
  • Never trust the browser. The shopper sends only a product id and quantity. The price comes from your code on the server. Do not read a price from request data.

Step 4: showing the discount

Shoppers need to see the deal before they add to cart. Print a small table after the price on the product page, and show the saving in the cart:

PHP
<?php
add_action( 'woocommerce_single_product_summary', function () {
    global $product;
    $table = Acme_Tier_Table::from_json( (string) $product->get_meta( '_acme_tiers' ) );
    if ( ! $table->has_tiers() ) {
        return;
    }
    echo '<table class="acme-tiers"><tbody>';
    foreach ( $table->to_array() as $min => $percent ) {
        printf(
            '<tr><th>%s</th><td>%s</td></tr>',
            esc_html( sprintf( __( 'Buy %d or more', 'acme-bulk' ), $min ) ),
            esc_html( sprintf( __( '%d%% off each', 'acme-bulk' ), $percent ) )
        );
    }
    echo '</tbody></table>';
}, 25 );

add_filter( 'woocommerce_cart_item_price', function ( $price_html, $item ) {
    $product = $item['data'];
    $regular = (float) $product->get_regular_price();
    if ( $regular > (float) $product->get_price() ) {
        return '<del>' . wc_price( $regular ) . '</del> ' . $price_html;
    }
    return $price_html;
}, 10, 2 );

Everything printed goes through esc_html(). The page is the same for every visitor, so it stays cacheable; the price table does not depend on the cart. Prices changed through set_price() exist only in the cart request, not on category pages, which is why a table on the product page is the honest way to advertise the deal.

Step 5: coupons and tiers

The order is: tier price first (cart hook), coupon afterwards (WooCommerce computes coupon discounts on the cart line totals). That means a 10% coupon on top of a 12% tier gives about 20.8% off in total, not 22%. Decide if that is acceptable. Typical choices:

Policy How to implement
Stack (default) Do nothing special
Tiers replace coupons Filter woocommerce_coupon_is_valid to reject coupons when a tier is active, with a clear message
Coupon replaces tiers In the cart hook, skip tiers when $cart->has_discount() is true (watch for loops: coupons recalculate totals)
Exclude tiered products from coupons A coupon's exclude products setting, or woocommerce_coupon_is_valid_for_product

The runnable check below makes the arithmetic of the "stack" policy explicit, and compares it with the "tiers replace coupons" policy:

PHP Stacking policies for tiers and coupons

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 "stack" saves 20.8%, not 22%, because the coupon works on a smaller number.

Step 6: tests

Because the engine is plain PHP, its tests need no WordPress at all. Cover the rules that matter, and test the WordPress edges separately with integration tests (see Testing WooCommerce Code):

PHP
<?php
it( 'applies the highest tier the quantity reaches', function () {
    $table = Acme_Tier_Table::from_text( "10,5\n50,12" );

    expect( $table->percent_for( 9 ) )->toBe( 0 );
    expect( $table->percent_for( 10 ) )->toBe( 5 );
    expect( $table->percent_for( 500 ) )->toBe( 12 );
} );

it( 'ignores invalid tier lines', function () {
    $table = Acme_Tier_Table::from_text( "abc\n1,50\n10,95" );

    expect( $table->to_array() )->toBe( [] );
} );

it( 'rounds the unit price once, half up', function () {
    expect( Acme_Pricing::unit_cents( 1999, Acme_Tier_Table::from_text( '10,5' ), 10 ) )->toBe( 1899 );
} );

Also add one integration test: add the product to a cart with quantity 10 and assert the cart line total, and another that changes the quantity back to 1 and expects the base price again, which catches the "discount sticks" bug.

Ideas to extend it

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the pricing logic kept in classes that do not call WordPress functions?

    Pure PHP classes need no database or hooks to test. The WordPress layer stays thin and is covered by a few integration tests.
  2. 2. In woocommerce_before_calculate_totals, where should the base price come from?

    The hook runs several times per request. Starting from the catalog price makes the result the same every time; reading a posted price would let shoppers set their own.
  3. 3. A 12% tier and a 10% coupon stack on a 25.00 item, quantity 20. About how much is saved in total?

    The coupon applies to the already reduced price: 0.88 times 0.90 is 0.792, so the saving is 20.8%.
  4. 4. Why does the engine round the unit price instead of the line total?

    Shoppers multiply the unit price by the quantity. Rounding per unit keeps the numbers on the page consistent with each other.

Summary

  • Keep the business rules (tier parsing, unit price, coupon order) in plain PHP and the WordPress glue thin.
  • Save validated tiers in product meta through the CRUD object; sanitize on input.
  • Change cart prices in woocommerce_before_calculate_totals idempotently, from the catalog price, and never from request data.
  • Advertise tiers with a cacheable price table on the product page.
  • Decide and document how tiers and coupons interact, and test the arithmetic.

Next: Project: A Bank-Transfer-Style Gateway