Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Products and the CRUD Layer

Variations, Attributes and Taxonomies

Create WooCommerce variable products in code: global and custom attributes, WC_Product_Variation, price ranges, syncing and keeping large variation sets fast.

A T-shirt in three colors and three sizes is not nine products to the shopper, but it is nine things to the store: nine prices, nine stock counts, nine SKUs. WooCommerce models this with a variable product (the parent the shopper sees) and variations (the purchasable children). The choices that distinguish the children, such as color and size, are attributes.

This lesson shows how those pieces fit together in code, the difference between global and custom attributes, how to create variations programmatically, and why the parent's price range needs syncing. It builds on Working With Products in Code and the CRUD ideas from CRUD Classes and Data Stores. WooCommerce itself cannot run on this site, so the real calls are read-only; the runnable examples are stand-ins for the matrix logic.

Parent, variations and attributes

A variable product has type variable and class WC_Product_Variable. It is not bought directly. Each variation is a WC_Product_Variation that stores its own price, SKU, stock and image, plus the attribute values that identify it. Behind the scenes a variation is a child record whose parent ID points at the variable product.

flowchart TD
    P["Variable product<br/>Trail Jacket (parent)"] --> A1["Attribute: Color<br/>red, blue"]
    P --> A2["Attribute: Size<br/>S, M"]
    P --> V1["Variation #1<br/>red / S<br/>SKU JK-RED-S"]
    P --> V2["Variation #2<br/>red / M"]
    P --> V3["Variation #3<br/>blue / S"]
    P --> V4["Variation #4<br/>blue / M"]

The parent lists the attributes and options; each variation picks one value per attribute.

The parent holds the shared data: name, description, categories, the list of attributes. The variations hold what differs. Shoppers choose from drop-downs on the product page; the page's script finds the variation that matches the chosen values and shows its price, stock and image.

Global versus custom attributes

Every attribute on a product is a WC_Product_Attribute object. There are two kinds, and the difference matters:

  • Global attributes are defined once in the store (Products, Attributes). Each one becomes a WordPress taxonomy whose name starts with pa_, for example pa_color. Its options are terms, so the same "Red" is shared by every product, can be used for filtering, and gets its own archive page.
  • Custom attributes exist only on one product. The options are plain strings stored inside the product's data. They cannot be used for store-wide filters, but they need no setup.

Creating a global attribute and its terms looks like this (read-only code, because it needs WordPress):

PHP
// Create the global attribute "Color" once (returns its numeric ID).
$attribute_id = wc_create_attribute( [
    'name'         => 'Color',
    'slug'         => 'color',
    'type'         => 'select',
    'has_archives' => false,
] );

if ( is_wp_error( $attribute_id ) ) {
    return; // for example, the slug already exists
}

// The taxonomy ("pa_color") is registered on the next request, on init.
$taxonomy = wc_attribute_taxonomy_name( 'color' ); // "pa_color"

Because the taxonomy is registered during init, a script that creates the attribute and uses it in the same request has to register the taxonomy first or insert the terms on a later request. A common pattern is to create the attribute on plugin activation and add terms with wp_insert_term( 'Red', 'pa_color' ) after init.

Use a global attribute when shoppers should filter by it or when many products share the values (color, size, brand). Use a custom attribute for one-off facts ("Pack contents" for a single kit).

Building a variable product

Attributes are attached to the parent with set_attributes(). Two flags decide how each one behaves: set_visible() shows it on the "Additional information" tab, and set_variation() marks it as one the variations are built from.

PHP
$product = new WC_Product_Variable();
$product->set_name( 'Trail Jacket' );

$color = new WC_Product_Attribute();
$color->set_id( wc_attribute_taxonomy_id_by_name( 'pa_color' ) ); // global: non-zero ID
$color->set_name( 'pa_color' );                                    // taxonomy name
$color->set_options( [ $red_term_id, $blue_term_id ] );            // global: term IDs
$color->set_position( 0 );
$color->set_visible( true );
$color->set_variation( true );

$fit = new WC_Product_Attribute();
$fit->set_id( 0 );                       // custom: ID zero
$fit->set_name( 'Fit' );                 // label shown to shoppers
$fit->set_options( [ 'Regular', 'Slim' ] ); // custom: plain strings
$fit->set_position( 1 );
$fit->set_visible( true );
$fit->set_variation( true );

$product->set_attributes( [ $color, $fit ] );
$parent_id = $product->save();

Notice how the same class describes both kinds: ID zero and string options mean custom; a taxonomy ID and term IDs mean global.

Each variation is then created as its own object:

PHP
$variation = new WC_Product_Variation();
$variation->set_parent_id( $parent_id );
$variation->set_attributes( [
    'pa_color' => 'red',     // global: the term SLUG
    'fit'      => 'Regular', // custom: the option text, keyed by sanitized name
] );
$variation->set_sku( 'JK-RED-REG' );
$variation->set_regular_price( '129.00' );
$variation->set_manage_stock( true );
$variation->set_stock_quantity( 12 );
$variation->save();

Two details trip people up. First, variation attributes use the slug for global terms, not the term ID or the display name. Second, an attribute left empty (or missing) on a variation means "Any": the variation matches every option of that attribute. That is useful for "same price for all sizes" and dangerous when you create it by accident.

The price range and syncing

A variable product has no single price. The shop loop shows "$89.00 โ€“ $129.00", computed from the children. WooCommerce stores the minimum and maximum so listings can be sorted and filtered quickly, and caches the full price map in a transient. After you create or change variations in code, the parent must be synced so those values are correct:

PHP
$parent = wc_get_product( $parent_id );
$parent->get_variation_price( 'min' ); // lowest active price
$parent->get_variation_price( 'max' ); // highest active price
$parent->is_on_sale();                 // true if any variation is on sale

WC_Product_Variable::sync( $parent_id );      // rebuild stored price/stock summary
wc_delete_product_transients( $parent_id );   // drop cached price maps

Saving a variation through the CRUD object normally triggers the data store's syncing, so you only need the explicit calls in unusual flows, such as bulk SQL updates (which you should avoid) or an importer that works in batches. If a shop shows a stale price range, a missed sync or a stale transient is the first thing to check.

The second stand-in below shows the range logic without WordPress: it also demonstrates the "Any" rule and how to find the variation for a shopper's selection.

PHP Matching a selection and building a price range

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.

Generating the matrix

Admin users click "Generate variations" and WooCommerce creates one child per combination. In code you do the same: take the Cartesian product of the variation attributes, skip combinations that already exist, then create what is missing. The number of combinations multiplies quickly: three colors, five sizes and four fits give 60 children.

PHP A variation matrix generator with a safety limit

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.

What is real: the combinatorics, the "skip existing" idea and the need for a limit. What is the stand-in: the plain arrays; in WooCommerce you would call new WC_Product_Variation() for each missing combination and save it.

Performance of large variation sets

Variations are full products, so a parent with hundreds of them is expensive in several places:

  • Product page. WooCommerce embeds variation data as JSON for the page's script. Above a threshold (30 by default, adjustable with the woocommerce_ajax_variation_threshold filter) it switches to looking up the matching variation through an AJAX request instead.
  • Admin editing. The variations panel loads children in pages, and saving many at once can hit PHP time or input-variable limits.
  • Your code. Looping over $product->get_children() and calling wc_get_product() on each one costs a query round for every child. Fetch only the fields you need, process in batches, and run big jobs in the background (see Background Processing With Action Scheduler).

A good design rule: keep real variation counts in the dozens, not thousands. If a product has an attribute with a huge number of options that do not affect price or stock (a free-text engraving, say), do not make it a variation attribute. Collect it as cart item data instead, which is the subject of The Cart and Session.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an empty attribute value on a variation mean?

    An empty value is the "Any" wildcard. It is useful for shared prices, but easy to create by mistake.
  2. 2. Which value do you use for a global attribute such as pa_color in set_attributes() on a variation?

    Variations store the slug of the term for taxonomy-based attributes, for example "red".
  3. 3. What is a key difference between global and custom attributes?

    Global attributes are backed by pa_* taxonomies, so their terms are shared and filterable. Custom attributes live on a single product.
  4. 4. Why should you be careful with huge numbers of variations?

    Cost grows with the number of children. Keep variation sets small and handle free-form options as cart item data.

Summary

  • A variable product (WC_Product_Variable) is the parent; each purchasable child is a WC_Product_Variation.
  • Global attributes are pa_* taxonomies with shared terms; custom attributes live on one product.
  • set_variation( true ) marks an attribute as one the variations are built from; variations use term slugs for global attributes.
  • An empty variation attribute means "Any".
  • Keep the parent's price range in step with WC_Product_Variable::sync() and transient clearing when you work outside the normal save path.
  • Generate combinations deliberately, skip existing ones, enforce a limit and batch the work.

Next: Custom Product Fields and Tabs