Reputation: 33
I am struggling with adding an attribute to a product.
I have an array of keywords that I would like to add to a product:
$clean_keywords = array('cake','cup cakes');
$term_taxonomy_ids = wp_set_object_terms( get_the_ID(), $clean_keywords, 'pa_keywords', true );
$thedata = Array('pa_keywords' => Array(
'name' => 'pa_keywords',
'value' => '',
'is_visible' => '0',
'is_taxonomy' => '1'
));
update_post_meta( get_the_ID(),'_product_attributes',$thedata);
This works fine, but it deletes all my other attributes attach to the product.
I think the solution is to get the current attributes and merge it with $thedata
variable... but not sure how to do this.
Any ideas?
Thanks
Upvotes: 3
Views: 2933
Reputation: 254483
You need to get existing product attributes first and insert your new product attribute in the array before saving it. Also I have added 2 missing arguments in the array…
So your code should be:
$product_id = get_the_ID();
$taxonomy = 'pa_keywords';
$clean_keywords = array('cake','cup cakes');
$term_taxonomy_ids = wp_set_object_terms( $product_id, $clean_keywords, $taxonomy, true );
// Get existing attributes
$product_attributes = get_post_meta( $product_id, '_product_attributes', true);
// get the count of existing attributes to set the "position" in the array
$count = count($product_attributes);
// Insert new attribute in existing array of attributes (if there is any)
$product_attributes[$taxonomy] = array(
'name' => $taxonomy,
'value' => '',
'position' => $count, // added
'is_visible' => '0',
'is_variation' => '0', // added (set the right value)
'is_taxonomy' => '1'
);
// Save the data
update_post_meta( $product_id, '_product_attributes', $product_attributes );
This should work now without removing existing data.
Upvotes: 5