'How can I add new attribute to existing product in woocommerce with native functions

I want to add a new attribute to an existing woocommerce product. I use this code

$pf = new WC_Product_Factory();

$product = $pf->get_product(76);


//Create the attribute object
$attribute = new WC_Product_Attribute();

$attribute->set_id( 0 ); 

//pa_color slug
$attribute->set_name( 'color' ); 

//Set terms slugs
$attribute->set_options( array(
   'blue',
) );

$attribute->set_position( 0 );

//If enabled
 $attribute->set_visible( 1 );

$product->set_attributes(array($attribute));

$id = $product->save();

this code working fine but I want to add attributes with terms, this code create custom product attribute. I want to create attribute like this image enter image description here

How can I create key-value attributes?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source