Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Cart and Pricing

Coupons in Code

Create and validate WooCommerce coupons in code: WC_Coupon, discount types, usage limits, validity filters, custom types and how discounts are calculated.

A coupon looks simple in the admin: a code, an amount, a few checkboxes. Behind it is a small rules engine. WooCommerce checks whether a code exists, whether it has expired, whether the cart qualifies, whether the shopper has used it too often, and only then works out how much each line should be reduced. If you build promotions, import coupons from another system, or sell a "welcome" discount from your own plugin, you need to know how to drive that engine from code.

This lesson covers the WC_Coupon class, the three built-in discount types, creating coupons programmatically, the filters that let you add your own validity rules, and the order in which discounts are calculated. The real WooCommerce code is read-only here because it needs WordPress. The runnable examples are stand-ins in plain PHP, working in integer cents (see Representing Money Correctly). For the business view of stacking and exclusions, read Building a Promotions Engine first or after.

The pieces of a coupon

A coupon is stored as a shop_coupon post (coupons are not part of HPOS; they stay in the posts tables), and you work with it through the CRUD class WC_Coupon, just like products (CRUD Classes and Data Stores). The built-in discount types are:

Type Meaning
percent A percentage off the cart's eligible lines.
fixed_cart A fixed amount off the whole cart, shared out across the eligible lines.
fixed_product A fixed amount off each unit of the eligible products.

Restrictions live on the same object: minimum and maximum spend, "individual use only", "exclude sale items", included and excluded products and categories, allowed email addresses, a usage limit overall and one per user, an expiry date, and a "free shipping" flag.

Creating a coupon programmatically

Use the setters, then save(). Codes are compared in lowercase, so pass them through the formatting helper (read-only):

PHP
<?php
function acme_create_welcome_coupon( string $email ): int {
    $coupon = new WC_Coupon();

    $coupon->set_code( wc_format_coupon_code( 'WELCOME-' . strtoupper( wp_generate_password( 6, false ) ) ) );
    $coupon->set_discount_type( 'percent' );
    $coupon->set_amount( 10 );                      // 10 percent
    $coupon->set_individual_use( true );            // cannot be combined with other coupons
    $coupon->set_exclude_sale_items( true );
    $coupon->set_usage_limit( 1 );                  // one use in total
    $coupon->set_usage_limit_per_user( 1 );
    $coupon->set_minimum_amount( '30' );            // spend at least 30.00
    $coupon->set_email_restrictions( array( $email ) );
    $coupon->set_date_expires( strtotime( '+14 days' ) );
    $coupon->set_description( 'Welcome offer created by the Acme plugin' );

    return $coupon->save();                         // returns the coupon ID
}

Notes:

  • Amounts and spend limits are strings (decimal numbers), like prices. Keep them as plain decimals, not formatted with currency symbols.
  • set_date_expires() accepts a timestamp or a WC_DateTime. Remember that an expiry means "until the end of that day" in the store's timezone in the admin, so test the boundary.
  • If you generate many coupons (a campaign of 10,000 codes), create them in batches from a background job rather than one web request; see Background Processing With Action Scheduler.
  • To load an existing coupon: new WC_Coupon( 'welcome10' ) accepts a code or an ID. Check $coupon->get_id(); it is 0 when the code does not exist.

To apply one to the current cart from your own code, call WC()->cart->apply_coupon( 'welcome10' ). It returns true or false and adds an error notice on failure, so the shopper sees why.

How validation works

When a code is applied, WooCommerce runs a series of checks and stops at the first failure. Roughly: does it exist, is it enabled and not expired, is the usage limit reached, is the cart total inside the spend limits, does the cart contain a qualifying product, are other coupons already applied that prevent it, is the shopper's email allowed. Each failure has an error code and a shopper-facing message. The engine is implemented around the WC_Discounts class, which also does the arithmetic later.

flowchart TD
    A["Shopper enters a code"] --> B["Load WC_Coupon"]
    B --> C["Built-in checks<br/>(exists, expiry, limits, spend, products)"]
    C -->|failed| X["Error notice shown"]
    C -->|passed| D["woocommerce_coupon_is_valid filters<br/>(your rules)"]
    D -->|invalid or exception| X
    D -->|valid| E["Calculate discount per line"]
    E --> F["Totals updated"]

Your own rules run after the built-in checks, and any failure stops the process with a message.

Adding your own rule

Hook woocommerce_coupon_is_valid. It receives the current validity (true if the built-in checks passed), the coupon and the WC_Discounts object. The documented way to refuse with a custom message is to throw an exception (read-only):

PHP
<?php
add_filter( 'woocommerce_coupon_is_valid', 'acme_welcome_coupon_first_order_only', 10, 3 );

function acme_welcome_coupon_first_order_only( bool $valid, WC_Coupon $coupon, WC_Discounts $discounts ): bool {
    if ( ! str_starts_with( $coupon->get_code(), 'welcome-' ) ) {
        return $valid;                       // not our coupon family
    }

    if ( is_user_logged_in() && wc_get_customer_order_count( get_current_user_id() ) > 0 ) {
        throw new Exception( __( 'This welcome offer is for first orders only.', 'acme' ), 100 );
    }

    return $valid;
}

Other filters you will meet: woocommerce_coupon_is_valid_for_product (is the coupon valid for one specific product, used by product-based types), woocommerce_coupon_error (rewrite an error message) and woocommerce_coupon_get_discount_amount (change the amount for a line). Return the incoming value when your condition does not apply, so you never break other plugins' rules.

Usage limits and counting

usage_limit and usage_limit_per_user are checked during validation against the coupon's stored usage count and the list of emails or user IDs that used it. The count is increased when an order reaches a paid state, not when the coupon is merely applied to a cart; WooCommerce also reverses the count if an order is cancelled or refunded in the right states. Two practical consequences:

  • Two shoppers can hold the same single-use code in their carts at once. The second one fails at checkout, where the check runs again. Never assume the cart check is final.
  • If you change order statuses in code (Order Statuses and the Order Lifecycle), use the normal status APIs so the usage bookkeeping keeps working.

Custom coupon types

You can add a discount type of your own, for example "buy one, get 50% off the cheapest item". There are two parts: make the type selectable, and calculate its amount. The pieces are woocommerce_coupon_discount_types (adds the label to the dropdown) and woocommerce_coupon_get_discount_amount (computes the discount for a line). Computing from the line's price and quantity inside the filter is possible but easy to get wrong with rounding and shared discounts across lines. For anything beyond a simple per-line rule, many teams prefer to leave coupons to the built-in types and add a fee (a negative line, see Dynamic Pricing, Fees and Discounts) that the engine does not need to know about. Choose by who must see the discount: a coupon shows up under "Coupon: CODE" with per-line discounts in reports; a negative fee is one visible line.

Calculation order

Discounts are applied in a fixed order, not just "the order the shopper typed them":

  1. Applied coupons are sorted by type: percentage coupons first, then fixed-product, then fixed-cart. (A filter lets a plugin change the sorting.)
  2. Each coupon reduces the eligible lines only (restrictions on products and categories apply).
  3. A setting called Calculate coupon discounts sequentially decides what a percentage is a percentage of. Off (the default), each percentage coupon is calculated from the line's original price, so two 10% coupons give 20%. On, each coupon works on what remains, so two 10% coupons give 19%.
  4. Fixed-cart amounts are split across the eligible lines in proportion to their value, and no line can go below zero. WooCommerce works in the smallest currency unit and hands out the leftover cents, so the line discounts add up to exactly the coupon amount.

The stand-in below uses its own simple rounding (half up), so its cents can differ from WooCommerce in edge cases. What it shows correctly is the shape of the rules: order, sequential versus not, proportional sharing and the cap at the line total.

Runnable stand-ins

PHP A coupon validator stand-in

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.

The validator returns the first failure, exactly like the real engine, which is why the order of checks decides which message a shopper sees. The second stand-in does the arithmetic: sorted types, sequential versus original-price percentages, and proportional sharing of a fixed amount.

PHP Applying coupons to cart lines

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.

Read the three blocks of output together: the second 10% coupon is worth a full 10% of the original price in the first run and only 10% of the remainder in the second. In the last run the fixed amount is shared across the three lines and the line discounts add up to exactly 5.00 more, because the leftover cents are handed out one by one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call creates a coupon in code?

    Coupons are CRUD objects like products. You set the code, type and restrictions with setters and persist with save(), which returns the ID.
  2. 2. What is the documented way to reject a coupon with your own message inside woocommerce_coupon_is_valid?

    The engine catches the exception and shows its message as the error. Returning the incoming value when your rule does not apply keeps other plugins' checks intact.
  3. 3. With "Calculate coupon discounts sequentially" off, two 10% coupons on the same line give how much off?

    Each percentage coupon is taken from the original price when the setting is off. With the setting on, the second coupon works on what is left, so the pair gives 19%.
  4. 4. Why can a single-use coupon still fail at checkout after the cart accepted it?

    Applying a code to a cart does not reserve it. The limit is re-checked at checkout, so only the first paid order consumes the single use.

Summary

  • Coupons are WC_Coupon CRUD objects: set the code, type (percent, fixed_cart, fixed_product) and restrictions, then save().
  • Validation stops at the first failure; add your own rules with woocommerce_coupon_is_valid and throw an exception with a clear message.
  • Usage limits are counted when orders are paid and are re-checked at checkout; do not treat the cart check as final.
  • Custom types are possible with the discount-type and discount-amount filters, but a negative fee is often simpler.
  • Percentage coupons run before fixed ones; the sequential setting decides whether percentages compound, and fixed amounts are shared proportionally.
  • The stand-ins reproduce the rules in integer cents; rounding in real WooCommerce can differ by a cent in edge cases.

Next: Taxes, Currency and Formatting