Create Programmatically a Variable Product and Two New Attributes in WooCommerce
Building a variable product directly from code within a WordPress plugin requires more than just setting a few fields on a WC_Product. The core difficulty lies in how WooCommerce handles attributes internally. When you create an attribute via the admin UI, WooCommerce doesn't just store the data; it creates a specific taxonomy in the database and establishes relationships between terms and posts. Attempting to bypass this by manually inserting rows into wp_terms, wp_term_taxonomy, or wp_post_terms often fails because the object model expects these entities to exist first.
To programmatically create a variable product with two new attributes without triggering an HTTP request (which is vital for plugin functionality), you must leverage the WooCommerce API methods in the correct order. The process is sequential: define the attribute, save it to ensure the taxonomy exists, and then attach it to the product.
Defining the Attribute Object
Before creating a variable product, you need to instantiate the WC_Product_Attribute objects. These objects hold the configuration for the attribute itself, such as its name, slug, and whether variations should be created automatically.
// Define the first attribute: Size
$attr1 = new WC_Product_Attribute();
$attr1->set_name( 'Size' );
$attr1->set_slug( 'size' );
$attr1->set_variation( true ); // Optional: set to false if you are managing variations manually later
// Define the second attribute: Color
$attr2 = new WC_Product_Attribute();
$attr2->set_name( 'Color' );
$attr2->set_slug( 'color' );
$attr2->set_variation( true );
Creating and Registering Attributes
The critical step that many developers miss is the registration of these attributes. You cannot simply assign them to the product object; you must add them to the global attribute registry first. This ensures that when WooCommerce saves the product, it recognizes the taxonomy and creates the necessary database entries in the wp_terms and wp_term_taxonomy tables.
// Add attributes to the registry
WC_Attribute::register( $attr1 );
WC_Attribute::register( $attr2 );
Once registered, you can proceed to create the parent variable product. This product will act as a container for the variations. You should set it to be virtual or downloadable if applicable, and ensure it has no stock status if you intend to manage inventory per variation.
$parent_product = new WC_Product_Variable();
$parent_product->set_name( 'Dynamic Variable Product' );
$parent_product->set_type( 'variable' );
$parent_product->set_regular_price( 100 ); // Base price or null
$parent_product->set_description( 'This product is generated programmatically.' );
Adding Attributes to the Product
Now that the attributes are registered globally, you add them to the specific product instance. This step links the global taxonomy to the specific product post ID in the wp_term_relationships table.
// Add the attributes to the product
$parent_product->set_attributes( array( $attr1, $attr2 ) );
Saving and Verifying
Finally, you must save the product. This triggers the database updates required to finalize the relationship between the product and its new attributes.
// Save the variable product
$parent_product->save();
After saving, it is good practice to verify that the attributes were created correctly by checking their slugs or names on the product page. If you encounter issues where the attributes appear empty or unrecognized, it is almost certainly because step two (WC_Attribute::register) was skipped or executed before the attribute object was fully populated.
Common Pitfalls with Direct Database Manipulation
The source material notes a common frustration: developers trying to solve this by directly manipulating database objects (WP_Query, direct table inserts) often run into race conditions or missing metadata dependencies. WooCommerce relies heavily on its internal consistency checks. For example, if you insert a row into wp_terms but fail to update the term_group or miss a required meta relationship in wp_term_meta, the product save will either fail silently or revert changes.
By using the provided classes (WC_Product_Attribute, WC_Product_Variable, and WC_Attribute), you abstract away these complexities. The library handles the necessary SQL joins and updates to ensure the taxonomy is recognized by the rest of the system, including the frontend variation dropdowns.
If you are building a plugin that needs to handle this logic repeatedly, encapsulating the steps into a helper method ensures consistency across your codebase. This approach avoids the need for external HTTP requests, keeping everything within the WordPress environment and leveraging the existing object model designed specifically for this purpose.