WooCommerce: Add a product attribute to the existing ones in a product

醉酒当歌 提交于 2019-12-11 06:45:34

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/47413936/woocommerce-add-a-product-attribute-to-the-existing-ones-in-a-product

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!