How to Create Physical Product Variations in WooCommerce Programmatically

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.

[cc lang="php" tab_size="2" lines="100"]
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' ); [/cc]

haris raza

Hi, I'm Haris Raza! With years of experience as a WordPress backend developer, I specialize in custom PHP development, WooCommerce plugin creation, and building custom themes from scratch. Whether it's developing WordPress plugins or customizing existing ones, my goal is to provide seamless and efficient solutions that meet your unique needs. When I'm not coding, you can find me keeping up with the latest tech trends and collaborating with fellow developers. Thanks for visiting, and happy coding http://www.wpharis.com