Woocommerce: adding a variation of an existing product with existing attributes

I am trying to figure out how to add variation to an existing product that is not an initially variable product.

So, I have a shirt with the goods, and I get one more of them in the warehouse in different colors, so my importer of the product needs to add a new version of this existing product.

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);

This adds color to my product, but destroys all my existing product attributes. Pulling the existing _product_attributes just gives me serialized attributes, so just adding a new option on top of everything doesn't work.

Any ideas?

+4
source share
2 answers

, 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) );
+1

.

get term_id product_type = variable

/**
    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

:)

-1

Source: https://habr.com/ru/post/1652431/


All Articles