Woocommerce:向具有现有属性的现有产品添加变体

Woocommerce: Adding a variation to existing product with existing attributes

我想弄清楚如何将变体添加到最初不是可变产品的现有产品。

所以我有一件产品衬衫,我又买了一件不同颜色的库存产品,所以我的产品进口商需要为这个现有产品添加新的变体。

wp_set_object_terms ($product_id, 'black', 'pa_color', 1);

$attr_data = Array(
            'pa_color'=>Array(
                'name' => 'pa_color',
                'value' => '',
                'is_visible' => '1',
                'is_variation' => '1',
                'is_taxonomy' => '1'
            )
        );
update_post_meta($product_id, '_product_attributes', $attr_data);

这为我的产品添加了颜色,但破坏了我在产品上的所有现有属性。拉出现有的 _product_attributes 只会给我序列化的属性,因此仅在所有内容之上添加新变体是行不通的。

有什么想法吗?

我遇到了同样的问题,刚刚解决了。

获取 term_id 对于 product_type = 变量

/**
    SELECT $wpdb->terms.term_id FROM $wpdb->terms, $wpdb->term_taxonomy 
    WHERE name = 'variable' 
    AND taxonomy = 'product_type'
    AND $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
    LIMIT 1
**/

$variable_term_id  = 4;

wp_set_object_terms( $product_id, $variable_term_id, 'product_type' , true); //for variable product

:)

基本上问题是 product_attribute 不是单个变量,而且 wp_set_object_terms

中似乎没有合并

我这样解决了我的问题:

wp_set_object_terms ($product_id, 'black', 'pa_color', 1);

        $attr_data = Array(
            'pa_color'=>Array(
                'name' => 'pa_color',
                'value' => '',
                'is_visible' => '1',
                'is_variation' => '1',
                'is_taxonomy' => '1'
            )
        );

        $product = new WC_Product($product_id);

        update_post_meta( $product_id, '_product_attributes', array_merge($product->get_attributes(), $attr_data) );