首页 > 解决方案 > How update product attributes programmatically?

问题描述

I use following code to add attributes to a product:

foreach ($_attributes as $name => $value) {
        wp_set_object_terms($post_id, $value, $name, true);
        $product_attributes[$name] = array (
            'name' => $name, // set attribute name
            'value' => $value, // set attribute value
            'is_visible' => 0,
            'is_variation' => 1,
            'is_taxonomy' => 1
        );
    }
update_post_meta($post_id, '_product_attributes', $product_attributes );

but it remove previous attributes I added in product edit in admin, like product brand or model. How can I update current product attributes without remove previous ones?

Thanks to help me.

标签: wordpresswoocommerceplugins

解决方案


您可以在更新之前简单地备份您的数据库内容,如下所示:

$tmpBk = get_post_meta($post_id, '_product_attributes',true);
update_post_meta($post_id, '_product_attributes', array_merge(tmpBk,$product_attributes) );

这应该足以保存您以前存储的值


推荐阅读