WooCommerce Change Product Global Attribute Value via CRUD for Simple Product [closed]

I’m not sure which WooCommerce version you’re using, but in the latest version (3.3.5), WC_Product_Attribute doesn’t have a set_taxonomy() method. So I changed that to:

$attribute_object->set_id( 1 ); // set the taxonomy ID

Secondly, here you should pass an array of term IDs and not a string: (in this example, 123 is the ID of the term Yes of the “Foil” or pa_foil taxonomy)

$attribute_object->set_options( 'yes' ); // incorrect
$attribute_object->set_options( [ 123 ] ); // correct

Anyway, here’s the code I used:

// Array of $taxonomy => WC_Product_Attribute $attribute
$attributes = $product->get_attributes();

$term = get_term_by( 'name', 'Yes', 'pa_foil' );
// Or use $term = get_term_by( 'slug', 'yes', 'pa_foil' );

// Attribute `options` is an array of term IDs.
$options = [ $term->term_id ];
// Or set a static ID: $options = [ 123 ];

$attribute_object = new WC_Product_Attribute();
$attribute_object->set_name( 'pa_foil' );
$attribute_object->set_options( $options );
$attribute_object->set_visible( 1 );
$attribute_object->set_variation( 0 );
$attribute_object->set_id( 1 );
$attributes['pa_foil'] = $attribute_object;

$product->set_attributes( $attributes );
$product->save();

Leave a Comment