WooCommerce:将产品属性添加到产品中的现有属性 [英] WooCommerce: Add a product attribute to the existing ones in a product
问题描述
我正在努力为产品添加属性.
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.
我认为解决方案是获取当前属性并将其与$thedata
变量合并...但是不确定如何执行此操作.
I think the solution is to get the current attributes and merge it with $thedata
variable... but not sure how to do this.
有什么想法吗?
谢谢
推荐答案
您需要先获取现有产品属性,然后将新产品属性插入数组中,然后再保存.另外我在数组中添加了2个缺少的参数…
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…
因此您的代码应为:
$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.
这篇关于WooCommerce:将产品属性添加到产品中的现有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!