WooCommerce:将产品属性添加到产品中的现有属性中

Amz*_*2nv 3 php wordpress attributes product woocommerce

我正在努力为产品添加属性。

我有一系列关键字想要添加到产品中:

$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);
Run Code Online (Sandbox Code Playgroud)

这工作正常,但它删除了我附加到产品的所有其他属性。

我认为解决方案是获取当前属性并将其与$thedata变量合并......但不知道如何执行此操作。

有任何想法吗?

谢谢

Loi*_*tec 5

您需要先获取现有的产品属性,然后在保存之前将新的产品属性插入数组中。我还在 array\xe2\x80\xa6 中添加了 2 个缺失的参数

\n\n

所以你的代码应该是:

\n\n
$product_id = get_the_ID();\n$taxonomy = \'pa_keywords\';\n$clean_keywords = array(\'cake\',\'cup cakes\');\n$term_taxonomy_ids = wp_set_object_terms( $product_id, $clean_keywords, $taxonomy, true );\n\n// Get existing attributes\n$product_attributes = get_post_meta( $product_id, \'_product_attributes\', true);\n\n// get the count of existing attributes to set the "position" in the array\n$count = count($product_attributes);\n\n// Insert new attribute in existing array of attributes (if there is any)\n$product_attributes[$taxonomy] = array(\n    \'name\' => $taxonomy,\n    \'value\' => \'\',\n    \'position\' => $count, // added\n    \'is_visible\' => \'0\',\n    \'is_variation\' => \'0\', // added (set the right value)\n    \'is_taxonomy\' => \'1\'\n);\n\n// Save the data\nupdate_post_meta( $product_id, \'_product_attributes\', $product_attributes );\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在应该可以正常工作,而无需删除现有数据。

\n