I am using this code to add custom attributes
$attributes = array(
array("name"=>"Size","options"=>array("S","L","XL","XXL"),"position"=>1,"visible"=>1,"variation"=>1),
array("name"=>"Color","options"=>array("Red","Blue","Black","White"),"position"=>2,"visible"=>1,"variation"=>1)
);
if($attributes){
$productAttributes=array();
foreach($attributes as $attribute){
$attr = wc_sanitize_taxonomy_name(stripslashes($attribute["name"])); // remove any unwanted chars and return the valid string for taxonomy name
$attr = 'pa_'.$attr; // woocommerce prepend pa_ to each attribute name
if($attribute["options"]){
foreach($attribute["options"] as $option){
wp_set_object_terms($product_id,$option,$attr,true); // save the possible option value for the attribute which will be used for variation later
}
}
$productAttributes[sanitize_title($attr)] = array(
'name' => sanitize_title($attr),
'value' => $attribute["options"],
'position' => $attribute["position"],
'is_visible' => $attribute["visible"],
'is_variation' => $attribute["variation"],
'is_taxonomy' => '1'
);
}
update_post_meta(11874,'_product_attributes',$productAttributes); // save the meta entry for product attributes
The result of this code I got added just product attribute Name without term values...
I searched about that very much but did not got any answer.
There is some mistakes in your code. Your main mistake: The attribute terms to save as product meta data (at the end) need to be an array of term IDs (instead of term names).
Try the following revisited code:
Tested and works.
Related: Create new product attribute programmatically in Woocommerce