How to Create Virtual Product Variations in WooCommerce Programmatically

In this tutorial, you will learn about creating virtual product variations programmatically in WooCommerce. These variations are ideal for digital products, as they don’t require physical shipping.

Here’s a quick guide to creating a virtual product variation.

Before proceeding, ensure that:

  • You have a variable product already created in WooCommerce.
  • You have the product ID of the parent variable product.
$variation = new WC_Product_Variation();
$variation->set_parent_id( $product_id );
$variation->set_attributes( array( 'attribute_magical' => 'Yes' ) );

$variation->set_sku( 'Qaisar-123' );
$variation->set_image_id( $featured_image_id );

// some basics
$variation->set_downloadable( true ); // default – false
$variation->set_virtual( true ); // default – false

$variation->set_stock_status( 'instock' ); // outofstock, onbackorder

// define prices
$variation->set_regular_price( 40 );
$variation->set_sale_price( 10 );

// set date range if applicable

$variation->set_date_on_sale_from( '2024-01-01' );
$variation->set_date_on_sale_to( '2026-01-01' );

$variation->set_description( 'Programmatically created variation' ); // your description

// downloadable variation
$variation->set_downloads( $downloads );
$variation->set_download_limit( 1 ); // Download limit if applicable
$variation->set_download_expiry( 7 ); // expiry time if applicable

$variation->save();

 

 

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!