I'm trying to figure out the way how to add variation to existing product that is not originally variable product.
So I have a product Shirt and I get another one of those in stock in different color so my product importer needs to add a new variation to this existing product.
wp_set_object_terms ($product_id, 'black', 'pa_color', 1);
$attr_data = Array(
'pa_color'=>Array(
'name' => 'pa_color',
'value' => '',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
)
);
update_post_meta($product_id, '_product_attributes', $attr_data);
This adds a color to my product but destroys all my existing attributes on the product. Pulling the existing _product_attributes just gives me serialized attributes so just adding the new variation on top of everything isn't working.
How can this be done?
Basically the problem is that product_attribute is not a single variable and it seems that there is no merge in wp_set_object_terms
I solved my problem like this:
wp_set_object_terms ($product_id, 'black', 'pa_color', 1);
$attr_data = Array(
'pa_color'=>Array(
'name' => 'pa_color',
'value' => '',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
)
);
$product = new WC_Product($product_id);
update_post_meta( $product_id, '_product_attributes', array_merge($product->get_attributes(), $attr_data) );