A
A
Alexander Stepanov2018-08-23 16:43:21
WordPress
Alexander Stepanov, 2018-08-23 16:43:21

How to create a programmatically variable product?

Greetings!
Just don't send it to Google right away, please.
I tried a hundred ways to make variations in WooCommerce programmatically - it doesn't work.
Please help!

// In a class constructor
        $this->brand_tax = wc_attribute_taxonomy_name( 'brand' );
        // Insert the main product first
        // It will be used as a parent for other variations (think of it as a container)
        // Insert the attributes (I will be using size and color for variations)
        $attributes = array(
            $this->brand_tax => array(
                'name' => $this->brand_tax,
                'value' =>'',
                'is_visible' => '1',
                'is_variation' => '1',
                'is_taxonomy' => '1'
            )
        );
        update_post_meta( $new_id, '_product_attributes', $attributes );
        // Assign sizes and colors to the main product
        wp_set_object_terms( $new_id, array( 'OFM', 'ITR' ), $this->brand_tax );
        // Set product type as variable
        wp_set_object_terms( $new_id, 'variable', 'product_type', false );
        $parent_id = $new_id;
        $variation = array(
            'post_title'   => 'Product #' . $parent_id . ' Variation',
            'post_content' => '',
            'post_status'  => 'publish',
            'post_parent'  => $parent_id,
            'post_type'    => 'product_variation'
        );
        // The variation id
        $variation_id = wp_insert_post( $variation );
        // Regular Price ( you can set other data like sku and sale price here )
        update_post_meta( $variation_id, '_regular_price', 2 );
        update_post_meta( $variation_id, '_price', 2 );
        // Assign the size and color of this variation
        update_post_meta( $variation_id, 'attribute_' . $this->brand_tax, 'OFM' );
        // Update parent if variable so price sorting works and stays in sync with the cheapest child
        WC_Product_Variable::sync( $parent_id );

Here is the last one I tried.
The product does not even want to become variable ..

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question