How to Create Physical Product Variations in WooCommerce Programmatically

In WooCommerce, a variable product has multiple variations that differ by attributes like size, color, or material. These variations allow customers to select the specific product option they need. To programmatically create these variations, you need to:

  1. Create a variable product.
  2. Define attributes for the product.
  3. Generate variations based on those attributes.

In this tutorial, we are going to learn the easiest way to create physical product variations in WooCommerce.
 

function create_and_configure_product_variation() {
    $product_id = 123;

    $featured_image_id = 456; // Replace with your image ID

    // Create a new product variation
    $variation = new WC_Product_Variation();
    $variation->set_parent_id( $product_id ); // Set the parent variable product ID

    // Set attributes for the variation
    $variation->set_attributes( array( 'attribute_magical' => 'Yes' ) );

    // Set SKU for the variation
    $variation->set_sku( 'SKU-123' );

    // Set the featured image for the variation
    $variation->set_image_id( $featured_image_id );

    // Enable stock management for the variation
    $variation->set_manage_stock( true );
    $variation->set_stock_quantity( 10 ); // Set stock quantity
    $variation->set_backorders( 'yes' ); // Allow backorders
    $variation->set_low_stock_amount( 2 ); // Set low stock threshold

    // Set dimensions for the variation
    $variation->set_weight( 10 ); // Weight in kg
    $variation->set_length( 11 ); // Length in cm
    $variation->set_width( 12 ); // Width in cm
    $variation->set_height( 13 ); // Height in cm

    // Set the shipping class for the variation
    $variation->set_shipping_class_id( 22 );

    // Set the price for the variation
    $variation->set_regular_price( 50 ); // Regular price

    // Save the variation
    $variation->save();

    echo 'Variation created and configured successfully.';
}

// Hook to run the function once
add_action( 'init', 'create_and_configure_product_variation' );

 

 

 

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!