Create and Manage WooCommerce Variable Products and Variations Programmatically

Create WooCommerce variable products and variations with PHP

Importing a catalogue from an old shop system often means hundreds of products with size and colour combinations. The WooCommerce CRUD classes create them in a few dozen lines: a WC_Product_Variable parent with its attributes, and one WC_Product_Variation per combination with price, SKU and stock.

Problem: 500 T-shirts with up to 12 size/colour variations each have to be created from a CSV export, with prices, SKUs and stock per variation.

Solution: Make sure the global attributes (pa_size, pa_color) and their terms exist, create the parent with WC_Product_Variable and a list of WC_Product_Attribute objects marked for variations, save it, then create a WC_Product_Variation for each row with set_parent_id() and set_attributes() using the term slugs, and finally sync the parent.

The function

function ha_create_variable_product( array $data ) {
    $attributes = [];
    foreach ( [ 'size' => 'pa_size', 'color' => 'pa_color' ] as $field => $taxonomy ) {
        $names    = array_unique( array_column( $data['variations'], $field ) );
        $term_ids = [];
        foreach ( $names as $name ) {
            $term = term_exists( $name, $taxonomy ) ?: wp_insert_term( $name, $taxonomy );
            if ( ! is_wp_error( $term ) ) {
                $term_ids[] = (int) $term['term_id'];
            }
        }
        $attribute = new WC_Product_Attribute();
        $attribute->set_id( wc_attribute_taxonomy_id_by_name( $taxonomy ) );
        $attribute->set_name( $taxonomy );
        $attribute->set_options( $term_ids );
        $attribute->set_visible( true );
        $attribute->set_variation( true );
        $attributes[] = $attribute;
    }

    $product = new WC_Product_Variable();
    $product->set_name( $data['name'] );
    $product->set_description( wp_kses_post( $data['description'] ?? '' ) );
    $product->set_sku( $data['sku'] ?? '' );
    $product->set_attributes( $attributes );
    $product->set_status( 'publish' );
    $parent_id = $product->save();

    foreach ( $data['variations'] as $row ) {
        $variation = new WC_Product_Variation();
        $variation->set_parent_id( $parent_id );
        $variation->set_attributes( [
            'pa_size'  => sanitize_title( $row['size'] ),
            'pa_color' => sanitize_title( $row['color'] ),
        ] );
        $variation->set_regular_price( (string) $row['price'] );
        $variation->set_sku( $row['sku'] );
        $variation->set_manage_stock( true );
        $variation->set_stock_quantity( (int) $row['stock'] );
        $variation->save();
    }

    WC_Product_Variable::sync( $parent_id );
    return $parent_id;
}

The global attributes must exist first (Products, Attributes, or wc_create_attribute()), because the taxonomy pa_size is registered only for existing attributes. The parent lists the term IDs, the variations use the term slugs: set_attributes() of a variation expects taxonomy => slug. sync() updates the price range and the stock status of the parent from its variations.

Usage

ha_create_variable_product( [
    'name'       => 'Organic T-shirt',
    'sku'        => 'TSHIRT',
    'variations' => [
        [ 'size' => 'M', 'color' => 'Red', 'price' => 29, 'sku' => 'TSHIRT-M-RED', 'stock' => 10 ],
        [ 'size' => 'L', 'color' => 'Red', 'price' => 29, 'sku' => 'TSHIRT-L-RED', 'stock' => 4 ],
    ],
] );

Running an import

For hundreds of products, run the function from WP-CLI (wp eval-file import.php) rather than in a web request, which would time out. Check for existing SKUs with wc_get_product_id_by_sku() first, so the import can be repeated without duplicates; set_sku() throws a WC_Data_Exception for a SKU that already exists, so wrap each product in try/catch and log the failures.

NOTE: For a one-off import, the built-in CSV importer (Products, Import) understands variations as separate rows with a parent SKU and may save writing code. Reading and changing existing variations: wc_get_product() and variations.