When adding variations to a WooCommerce product it is adding in a blank attribute. Meaning that when I try to add in my own attribute it gets appended to an existing array.
Example code I am running:
$product_variation = wc_get_product( $variation_id ); $product_variation->set_attributes(array('attribute_pa_varinfo' => 'blue')); $product_variation->save();
Then when I var_dump($product_variation);
I get the following:
["attributes"]=> array(2) { [0]=> string(0) "" ["pa_varinfo"]=> string(4) "5034" }
So when I view the product in WooCommerce admin all my variations are there but the attribute is stuck at “any option” for all of them.
The weird thing is when I then “update” the product from wp-admin all of the variations then get the correct attribute selected.
Has anyone encountered this before or got any ideas of what I can do?
As another example if I run the following:
$product_variation = wc_get_product( $variation_id ); $product_variation->set_attributes( array ( 'simon' => 'confused' ) ); $product_variation->save(); var_dump($product_variation->get_attributes());
This returns:
array(2) { [0]=> string(0) "" ["simon"]=> string(8) "confused" }
Where does the first item come from? I can’t seem to clear it.
Advertisement
Answer
So it turns out the problem was with the actual setting up of the attribute against the main parent product, I was passing through an unnamed array, by adding wc_attribute_taxonomy_name('varinfo') =>
(line 2 below) this correctly saves the data and removes the blank array I had.
$product_attributes = array( wc_attribute_taxonomy_name('varinfo') => array ( 'name' => wc_attribute_taxonomy_name( 'varinfo' ), // set attribute name 'value' => '', // set attribute values 'position' => 1, 'is_visible' => 1, 'is_variation' => 1, 'is_taxonomy' => 1 ) ); update_post_meta($post_id, '_product_attributes', $product_attributes);