DEV Community

Cover image for How to Add Product Variations in WooCommerce (Without Wrecking Your Database)
Istiak Ahamed
Istiak Ahamed

Posted on Originally published at kinetix.software

How to Add Product Variations in WooCommerce (Without Wrecking Your Database)

Nothing kills a store manager's afternoon faster than building a 48-variant apparel listing in WooCommerce, hitting Update, and watching the frontend product page load with dead dropdowns or a "This product is currently out of stock and unavailable" banner.

Most tutorials searching for WooCommerce how to add product variations show you three screenshots of a T-shirt in Red and Blue, tell you to click Save, and call it a day. They skip the part that actually breaks production stores: picking the wrong attribute scope, blowing past WooCommerce's hardcoded 30-variant AJAX threshold, or creating hundreds of orphaned child rows in wp_posts and wp_postmeta that choke your database queries during checkout.

If you sell items with sizes, colors, materials, or hardware tiers, your catalog architecture depends on getting variable products right the first time. Below is the exact workflow for building, bulk-editing, and scaling WooCommerce product variations without slowing down your server or rebuilding your catalog six months from now.


Simple Products vs. Variable Products: The Architectural Trade-Off

Before touching the WordPress admin, you need to know what happens under the hood when you switch a product from Simple to Variable.

In WooCommerce, a Simple Product is a single row in the wp_posts table (post_type = 'product') with its price, SKU, and inventory stored in wp_postmeta and indexed in wp_wc_product_meta_lookup.

A Variable Product is a parent container (post_type = 'product'). Every single variation you generate creates a separate child post in wp_posts (post_type = 'product_variation', linked via post_parent), complete with roughly 15 to 25 meta rows per variation in wp_postmeta.

Metric / Dimension Simple Product Variable Product Single-SKU Split (Alternative)
Best Use Cases Single-option goods, digital downloads, fixed hardware, books Apparel (Size × Color), tiered licenses, multi-finish furniture High-ticket items where each color needs its own Google Shopping URL and gallery
Admin Setup Time 1–2 minutes per item 5–15 minutes per parent item (depending on matrix size) 3–5 minutes per item (cloning + cross-linking)
Database Footprint 1 row in wp_posts + ~20 rows in wp_postmeta 1 + N rows in wp_posts + (N × ~22) rows in wp_postmeta 1 row per SKU in wp_posts, no parent-child join overhead
Catalog Filtering Fast direct meta/taxonomy lookup Requires joining child variation stock/price via wp_wc_product_meta_lookup Fast direct lookup; clutters archive grids unless grouped
SKU & Stock Granularity One SKU and stock counter for the entire product Independent SKU, price, weight, dimensions, image, and stock per child variant Independent SKU, URL, canonical tag, and review pool per item
Frontend Payload Zero variation JSON in DOM Inline JSON payload for ≤ 30 variations; wc-ajax=get_variation XHR above 30 Zero variation JSON in DOM

Deep Dive: Why WooCommerce variation limits crash your site

When you combine multiple attributes, variation counts multiply combinatorially ($A \times B \times C$). Consider a custom sneaker listing with 10 sizes, 8 colorways, and 3 width options. That single product generates $10 \times 8 \times 3 = 240$ child rows of post_type = 'product_variation'.

Assuming 22 wp_postmeta entries per variation (_sku, _regular_price, _sale_price, _price, _stock, _stock_status, _manage_stock, _weight, _length, _width, _height, _thumbnail_id, plus attribute_pa_* keys), that single sneaker listing injects 5,280 rows into wp_postmeta.

Three bottlenecks hit you when variations scale recklessly:

  1. The Admin Batch Generation Cap (WC_MAX_LINKED_VARIATIONS): WooCommerce caps the "Generate variations" bulk tool at 50 variations per execution (WC_MAX_LINKED_VARIATIONS = 50) so PHP doesn't hit max_execution_time or exhaust memory_limit while firing save_post hooks and regenerating product lookup tables 50 times in a row.
  2. The Frontend JSON vs. AJAX Cutoff (woocommerce_ajax_variation_threshold): By default, if a variable product has 30 or fewer published variations, WooCommerce serializes all variation objects—including HTML price strings, image srcset metadata, dimensions, and availability rules—into the data-product_variations attribute on `. The browser filters dropdown combinations instantly in memory. The moment you hit **31 variations**, WooCommerce stops embedding the JSON array and falls back to firing an uncached/?wc-ajax=get_variation` POST request on every dropdown change. Worse, because the browser no longer knows which combinations exist ahead of time, every attribute term appears selectable until the shopper picks all dropdowns and gets hit with an "unavailable" notice.
  3. Unindexed wp_postmeta Joins: Poorly coded third-party swatch plugins or legacy filter widgets often run INNER JOIN wp_postmeta across multiple attribute_pa_* keys without using WooCommerce's wp_wc_product_attributes_lookup table introduced in WooCommerce 6.3+. On a store with 500 variable products and 40,000 child variations, a single uncached category filter query can lock MySQL CPU at 100%.

How WooCommerce Assigns Attributes to Variations (Architecture Flowchart)

Before clicking around the product editor, look at how WooCommerce connects taxonomies, parent product settings, and child variations. Every broken variation setup traces back to a missing link in this chain:

flowchart TD
    A["Parent Product (wp_posts: product)"] --> B{"Product Data Type?"}
    B -->|"Simple Product"| C["Single Price & SKU in wp_postmeta"]
    B -->|"Variable Product"| D["Assign Product Attributes"]

    D --> E["Global Attributes (Taxonomy: pa_color, pa_size)"]
    D --> F["Custom Product Attributes (Serialized in _product_attributes)"]

    E --> G{"Check 'Used for variations'?"}
    F --> G

    G -->|"No"| H["Displayed in 'Additional Information' Tab Only"]
    G -->|"Yes"| I["Exposed to Variations Generator"]

    I --> J["Create Child Rows (wp_posts: product_variation)"]
    J --> K{"Does Each Variation Have Regular Price?"}

    K -->|"No (Blank)"| L["Hidden on Frontend / Marked Unavailable"]
    K -->|"Yes (Price >= 0)"| M{"Total Variations <= 30?"}

    M -->|"Yes"| N["Preload JSON in data-product_variations (Instant UI)"]
    M -->|"No (> 30)"| O["Fallback to wc-ajax=get_variation on Selection"]

Notice the two failure points in that diagram:

  1. Forgetting to enable Used for variations under the Attributes tab leaves the Variations tab completely empty.
  2. Leaving the Regular price field blank on generated child variations causes WooCommerce to hide those variations on the frontend—even when stock is set to In stock.

Step-by-Step Execution Guide: Adding Product Variations in WooCommerce

Follow these four steps in exact order. Skipping Step 1 is the number-one reason store owners end up redoing their catalog when they add layered navigation filters later.

Step 1: Configure Global Attributes vs. Custom Product Attributes

When store owners search WooCommerce how to add product variations, they usually jump straight into a product post and type sizes into the local attribute box. Stop doing that.

WooCommerce supports two distinct attribute storage engines:

  1. Global Attributes (Products > Attributes): Stored as dedicated WordPress custom taxonomies (pa_size, pa_color, pa_material) in wp_terms and wp_term_taxonomy.
  2. Custom Product Attributes (Created inside a single product): Stored as a serialized PHP array inside the _product_attributes row in wp_postmeta for that single product ID only.

When to Use Global Attributes vs. Custom Product Attributes (Decision Matrix)

Use Global Attributes for 95% of your catalog:

  • Archive Filtering & Faceted Search: WooCommerce's Filter Products by Attribute block, FacetWP, Filter Everything, and AJAX swatch filters can only index Global Attributes cleanly because they query taxonomy term relationships (wp_term_relationships) and the wp_wc_product_attributes_lookup table.
  • Bulk Management: If you rename "Charcoal" to "Slate Grey" under Products > Attributes > Color, every product using that global term updates automatically. With custom attributes, you have to open and edit 200 products manually.
  • Color & Image Swatch Plugins: Almost all variation swatch systems attach hex codes or texture thumbnails to global taxonomy term meta (wp_termmeta).

Use Custom Product Attributes only when:

  • An attribute is 100% unique to a single one-off product and will never be used as a shop sidebar filter (for example, a custom bundle choosing between "Include calibration certificate" and "Standard packaging only" on a single piece of lab equipment).

How to Create a Global Attribute Properly

  1. In your WordPress sidebar, go to Products > Attributes.
  2. Under Add new attribute, enter the Name (e.g., Size or Color).
  3. Leave Slug blank to auto-generate a clean slug (e.g., size), or define a short lowercase slug manually.
  4. Set Default sort order to Custom ordering. (Do not pick "Name" for clothing sizes—alphabetical sorting orders sizes as L, M, S, XL, XS instead of XS, S, M, L, XL.)
  5. Click Add attribute.
  6. In the table on the right, find your newly created attribute and click Configure terms.
  7. Add each option individually (e.g., Small, Medium, Large, X-Large) and click Add new Size. Drag the three-bar handle on the right side of the terms table to arrange them in logical order.

Step 2: Activate the "Variable Product" Data Setting

Once your global attributes and terms exist, open the product you want to configure:

  1. Go to Products > Add New (or open an existing product under Products > All Products).
  2. Enter your product title, main description, and assign your Product categories in the right sidebar.
  3. Scroll down to the Product data meta box.
  4. Click the dropdown next to Product data — (which defaults to Simple product) and select Variable product.
  5. Notice how the left-hand tab column changes immediately: the General tab disappears (because base pricing now lives on individual variations), and the Variations tab appears below Attributes.

Pro Tip on Parent-Level SKUs and Inventory: Click the Inventory tab before leaving this step. You can set a master SKU for the parent container (e.g., KTX-HOODIE-BASE), which helps ERP and warehouse integrations group child SKUs (KTX-HOODIE-BLK-S, KTX-HOODIE-BLK-M). However, leave Track stock quantity for this product unchecked at the parent level unless all variations draw from a single shared physical pool (such as raw fabric printed on demand).


Step 3: Assign Attributes and Generate the Variations

Now you will bind your global attributes to the parent product and generate the child variation records.

Part A: Attach Attributes to the Product

  1. Inside the Product data box, click the Attributes tab on the left.
  2. In the Add existing dropdown (labeled Addexisting attribute in WooCommerce 7.8+), select your global attribute (e.g., Color).
  3. Click the Values input field:
    • Click Select all if this product comes in every color you created globally.
    • Or click inside the box to pick specific terms (Obsidian Black, Crimson, Slate).
  4. Verify two checkboxes directly below the attribute name:
    • Visible on the product page: Keep checked if you want the attribute listed in the "Additional information" specs table.
    • Used for variations: Must be checked. (In WooCommerce 7.8+, switching to Variable product first auto-checks this box; if you added attributes before switching from Simple to Variable, you must check Used for variations manually.)
  5. Repeat for your second attribute (e.g., select Size from the Add existing dropdown and pick S, M, L, XL).
  6. Click the blue Save attributes button at the bottom left of the Attributes panel. Wait for the AJAX spinner to finish before moving on.

Part B: Generate the Child Variations

  1. Click the Variations tab on the left side of the Product data box.
  2. You have two buttons in the center of the empty state:
    • Generate variations: Automatically builds the Cartesian product ($Color \times Size$) of every attribute term you added in Step 3A, up to 50 variations per click.
    • Add manually: Creates a single blank variation row where you pick attribute dropdowns by hand.
  3. Click Generate variations, then click OK in the browser confirmation dialog ("Do you want to generate all variations? This will create a new variation for each and every possible combination of variation attributes (max 50 per run).").
  4. If you have combinations you don't actually manufacture (e.g., Crimson in XS), hover over that specific variation row and click the red Remove link on the right, or leave specific dropdowns set to Any Size if price, SKU, and stock are identical across all sizes of a given color.

Step 4: Set Prices, SKUs, Images, and Stock Status in Bulk

Never expand 30 variation rows one by one just to type $49.00 thirty times. Use WooCommerce's built-in bulk actions bar and row-level overrides.

1. Set Base Pricing in Bulk (Mandatory)

Every variation must have a Regular price (even if it is 0), or WooCommerce will refuse to display it on the frontend.

  1. At the top of the Variations tab, click the Bulk actions dropdown (in older WooCommerce versions, this dropdown reads Add variation; in WooCommerce 8.x+, you can also check specific rows or click Bulk actions > Pricing > Set regular prices).
  2. Select Set regular prices under the Pricing optgroup and click Go (or select it directly from the new toolbar).
  3. In the browser prompt, type your base price (e.g., 49.00 — numbers and decimal point only, no currency symbols) and click OK.
  4. Price Upcharges for Specific Sizes (e.g., XXL costs +\$5): If all variations cost \$49.00 except XXL which costs \$54.00, set all regular prices to 49.00 in bulk first, then expand only the XXL rows and change their Regular price ($) to 54.00 (or use Bulk actions > Increase regular prices (fixed amount or percentage) on filtered rows).

2. Set Stock Status or Stock Quantities in Bulk

If you track inventory per SKU:

  1. Open the Bulk actions dropdown and select Toggle "Manage stock" under Inventory.
  2. Open Bulk actions again, select Stock under Inventory, and enter your starting inventory count (e.g., 25).
  3. Next, click each variation row to expand it and enter its unique SKU (e.g., KTX-TEE-BLK-S, KTX-TEE-BLK-M).
  4. Assign a Variation Image: Click the blue image placeholder icon inside the top-left of each expanded variation row. When a shopper selects Crimson on the frontend, WooCommerce automatically swaps the main product gallery photo to this variation image.
  5. Click Save changes at the bottom of the Variations panel, then click the main blue Update / Publish button in the top-right corner of the WordPress editor.
Bulk Action Option in Variations Tab What It Modifies in wp_postmeta Best Practical Use Case
Set regular prices Updates _regular_price and _price across all child variations Initializing baseline pricing so all variations become purchasable immediately
Increase / Decrease regular prices Adjusts _regular_price by fixed amount (5.00) or percentage (10%) Applying raw material cost increases across a 40-variant matrix in 5 seconds
Set scheduled sale prices Populates _sale_price, _sale_price_dates_from, and _sale_price_dates_to Scheduling a weekend flash sale that starts and expires automatically at midnight
Toggle "Manage stock" Flips _manage_stock between yes and no Switching from simple "In Stock / Out of Stock" flags to exact unit counting
Set Weight / Dimensions Updates _weight, _length, _width, _height Ensuring live USPS/UPS/FedEx shipping calculators quote accurate rates

Advanced Code Snippet: Raising the WooCommerce AJAX Variation Limit & Batch Cap

Once a product passes 30 variations, WooCommerce disables client-side variation matching. Watch what happens on the frontend when a product has 36 variations (for example, 6 colors × 6 sizes) and 10 of those combinations are out of stock:

  • With 30 or fewer variations: As soon as the shopper clicks Color: Obsidian, WooCommerce grays out or hides unavailable sizes (S, XL) immediately because the full variation map is already loaded in the browser's DOM.
  • With 31+ variations: The shopper can pick Color: Obsidian and Size: XL—even though XL is sold out—and only after selecting both does an AJAX call return "Sorry, this product is unavailable. Please choose a different combination." That friction tanks conversion rates.

Drop the following snippet into your child theme's functions.php file or a lightweight mu-plugin (wp-content/mu-plugins/kinetix-woo-variations.php) to raise the frontend inline JSON threshold cleanly based on product complexity, and optionally increase the backend batch generation limit:

<?php
/**
 * Plugin Name: Kinetix WooCommerce Variation Optimizer
 * Description: Raises the frontend AJAX variation threshold so out-of-stock combinations
 *              disable immediately in the UI, and bumps backend batch generation cap.
 */

defined( 'ABSPATH' ) || exit;

/**
 * 1. Increase the frontend AJAX variation threshold from 30 to 120.
 *    Keeps variation matching instantaneous in the browser and prevents
 *    shoppers from selecting out-of-stock attribute combinations.
 *
 * @param int        $qty     Default threshold (30).
 * @param WC_Product $product Current variable product object.
 * @return int
 */
add_filter( 'woocommerce_ajax_variation_threshold', function( $qty, $product ) {
    // Safe sweet spot for modern hosting & gzipped HTML payloads: 100-150 variations.
    // Above 150 variations, keep AJAX fallback to avoid bloating initial HTML DOM size.
    return 120;
}, 10, 2 );

/**
 * 2. Increase the backend "Generate variations" batch size from 50 to 150.
 *    Only define if not already set in wp-config.php.
 */
if ( ! defined( 'WC_MAX_LINKED_VARIATIONS' ) ) {
    define( 'WC_MAX_LINKED_VARIATIONS', 150 );
}

/**
 * 3. Strip unnecessary image metadata from the frontend variation JSON payload
 *    to keep HTML page weight lean when raising the variation threshold.
 *
 * @param array                $variation_data Array of serialized variation properties.
 * @param WC_Product_Variable  $product        Parent variable product.
 * @param WC_Product_Variation $variation      Child variation object.
 * @return array
 */
add_filter( 'woocommerce_available_variation', function( $variation_data, $product, $variation ) {
    if ( isset( $variation_data['image'] ) && is_array( $variation_data['image'] ) ) {
        // Remove EXIF/camera metadata from inline JSON payload; keep src, srcset, sizes, alt.
        unset(
            $variation_data['image']['caption'],
            $variation_data['image']['description'],
            $variation_data['image']['title']
        );
    }
    return $variation_data;
}, 10, 3 );
Enter fullscreen mode Exit fullscreen mode

Performance Note: Why include the third filter (woocommerce_available_variation)? Every variation in the inline JSON payload weighs roughly 1.2 KB to 2 KB uncompressed. At 120 variations, stripping unused image caption/description properties shaves 25–40 KB off the inline HTML before Brotli/Gzip compression even touches it.

Want the variation form higher up the page, or the price above the title? Don't copy content-single-product.php to do it. The hook priorities and block template options in how to edit a WooCommerce product page without a builder move the add-to-cart form with two lines of PHP and keep your layout update-safe.


Troubleshooting the 3 Most Common WooCommerce Variation Errors

Even experienced developers run into silent failures when migrating or bulk-importing variable products. Open the matching accordion below to fix the exact issue you are seeing.

Error 1: "This product is currently out of stock and unavailable" (Even Though Variations Are In Stock)

Why It Happens:
This message triggers when WooCommerce evaluates $product-&gt;get_available_variations() on the single product template and receives an empty array ([]). In 9 out of 10 stores, the variations are in stock, but their Regular price field is empty, or the parent-level Inventory tab has Manage stock enabled with a Stock quantity of 0.

Step-by-Step Fix:

  1. Open the product editor and click Product data > Inventory. Verify that Track stock quantity for this product is unchecked at the parent level (or has a positive integer if intentionally shared).
  2. Click the Variations tab, open Bulk actions, select Set regular prices, and enter your price.
  3. Expand one variation row and verify that the Enabled checkbox (next to Downloadable and Virtual) is checked.
  4. Click Save changes and Update the product.
  5. Still showing out of stock after a CSV import? Go to WooCommerce > Status > Tools and click Regenerate next to Product lookup tables (wp_wc_product_meta_lookup) and Clear transients next to WooCommerce transients.

Error 2: Attribute Dropdowns Are Missing or Out-of-Stock Combinations Still Appear Clickable

Why It Happens:

  • Missing Dropdowns: Either the attribute was saved without Used for variations checked, or the generated variations still have their attribute dropdowns set to Any [Attribute] while no specific terms were assigned under the Attributes tab.
  • Out-of-Stock Combinations Still Clickable: Your product has more than 30 variations (exceeding woocommerce_ajax_variation_threshold), or WooCommerce > Settings > Products > Inventory > Out of stock visibility ("Hide out of stock items from the catalog") is unchecked while your theme doesn't grey out is_in_stock: false variants.

Step-by-Step Fix:

  1. Add the woocommerce_ajax_variation_threshold filter from the PHP code snippet above so products up to 120 variations evaluate stock combinations client-side.
  2. Go to WooCommerce > Settings > Products > Inventory and check Out of stock visibility if you want zero-stock variations excluded from selectable attribute combinations.
  3. Clear your object cache (Redis / Memcached) and page cache after saving. WooCommerce caches visible variation IDs in a transient named wc_product_children_.

Error 3: Adding Variations Fails Silently or Only Saves the First 20–30 Rows

Why It Happens:
When you expand and edit dozens of variations in the classic WordPress product editor and click Save changes, the browser sends a massive POST payload containing hundreds of form inputs (variable_post_id[], variable_sku[], variable_regular_price[], variable_stock[], etc.). Each variation row submits roughly 25 to 35 input fields. If you edit 40 variations at once, the request sends over 1,200 POST variables.

Default PHP configurations set max_input_vars = 1000. PHP silently drops every form field past the 1,000th variable without throwing a visible WordPress error, leaving half your variations unsaved or wiped.

Step-by-Step Fix:
Increase max_input_vars to 5000 (or 10000 for large catalogs) in your server's php.ini or .user.ini:

max_input_vars = 5000
post_max_size = 64M
max_execution_time = 120
Enter fullscreen mode Exit fullscreen mode

Verify the new limit took effect under Tools > Site Health > Info > Server > PHP max input variables.


Build High-Converting Variable Product Pages Without Bloat

Setting up product variations in WooCommerce comes down to three non-negotiable habits:

  1. Build Global Attributes (Products > Attributes) with Custom ordering so your catalog filters and variation lookup tables stay fast.
  2. Use Bulk actions to populate prices and stock across child variations in seconds rather than editing rows one by one.
  3. Tune woocommerce_ajax_variation_threshold and max_input_vars so large variant matrices never frustrate shoppers or drop data on save.

Once the data model is right, the product template and checkout funnel are the next bottlenecks: reordering the summary, trimming gallery scripts and replacing jQuery tabs is covered step by step in our WooCommerce product page editing guide, pruning billing fields with HPOS CRUD is covered in how to edit the WooCommerce checkout page without a builder, and our WordPress custom block theme development guide shows how to pair WooCommerce with a lean theme.json v3 frontend.

Running your store on Kinetix? Pair your clean variable product architecture with zero-layout-shift templates and sub-second page loads. Explore the Kinetix Documentation or view our plans to ship a faster WordPress storefront today.


Related Content


Originally published at https://kinetix.software/blog/woocommerce-how-to-add-product-variations.

Top comments (0)