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

I have a simple Woocommerce product and a global attribute named Foil (slug: foil)(pa id: pa_foil). The Foil Attribute can have two values Yes (slug: yes), or No (slug: no).

I now have simple product 49 and it has assigned the attribute “Foil” with a value of “No”. I want to change the value to “Yes” programmatically using CRUD. Here is my code:

global $woocommerce;
$product = wc_get_product('49');
$attribute_object = new WC_Product_Attribute();;
                    $attribute_object->set_name( 'pa_foil' );
                    $attribute_object->set_options( 'yes' );
                    $attribute_object->set_visible( 1 );
                    $attribute_object->set_variation( 0 );
                    $attribute_object->set_taxonomy ( 1 );
                    $attributes[] = $attribute_object;
$product->set_attributes( $attributes );
$product->save();

What it does is it create a new Custom Product Attribute named pa_foil with an empty value. How do I get it to apply the global Product Attribute Foil and set the predefined “No” value?

1 Answer
1

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