2
votes

I have already added some product to my WooCommerce, programmatically with two attributes (pa_size, pa_color). Both of them are used for variations. Now i want to make a php file, that it will insert one more attribute in each product (pa_brand). This will be used only for visibility and not for variations.

I tried some codes like:

$term_taxonomy_ids = wp_set_object_terms( $productID, $productBrand, 'pa_brand', true );

    $thedata = Array('pa_brand'=>Array(
        'name'=>'pa_brand',
        'value'=>$productBrand,
        'is_visible' => '1',
        'is_taxonomy' => '1'
    ));

    update_post_meta(  $productID,'_product_attributes',$thedata);

But my problem is that this way, adds the brand attribute, but the attributes i had already are getting lost.

The result is that i get all products with only one attribute.

Is there any way just to add one more attribute, without losing anything of the previous (attributes -

2

2 Answers

2
votes

update_post_meta() will always change the value when it is called - you need to get the existing meta data first and store that in the array too:

$term_taxonomy_ids = wp_set_object_terms( $productID, $productBrand, 'pa_brand', true );

$existingData['pa_size'] = get_post_meta($productID, 'pa_size', true);
$existingData['pa_color'] = get_post_meta($productID, 'pa_color', true);

$thedata = Array(
    'pa_brand'=>Array(
        'name'=>'pa_brand',
        'value'=>$productBrand,
        'is_visible' => '1',
        'is_taxonomy' => '1'
    ),
    'pa_size' => Array(
        'name'=>'pa_size',
        'value'=>$existingData['pa_size'],
        'is_visible' => '1',
        'is_taxonomy' => '1'
    ), 
    'pa_color' => Array(
        'name'=>'pa_color',
        'value'=>$existingData['pa_color'],
        'is_visible' => '1',
        'is_taxonomy' => '1'
    )
);

update_post_meta(  $productID,'_product_attributes',$thedata);
1
votes

Finally, in the last line i added this:

wp_set_object_terms( $productID, $productBrand, 'pa_brand' , true);

and now seems to not having any problems. I hope it will help you too.