我正在努力为产品添加属性。
我有一组要添加到产品中的关键字:
$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);
这工作正常,但它删除了我附加到产品的所有其他属性。
我认为解决方案是获取当前属性并将其与 $thedata
变量合并...但不确定如何执行此操作。
有什么想法吗?
谢谢
最佳答案
您需要先获取现有的产品属性,然后在保存之前将新的产品属性插入到数组中。我还在数组中添加了 2 个缺少的参数......
所以你的代码应该是:
$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 );
这应该可以在不删除现有数据的情况下工作。
关于php - WooCommerce:将产品属性添加到产品中的现有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413936/