1

I have some custom attributes for each product in woocommerce, I can edit them at the Attributes tab. I can also read them using this code

$product = new WC_Product($product_id);
$v = $product->get_attribute('myattr_name');

But I don't understand how to set this attribute value. Googling not helps. Do you know? I am looking for something like this

$product->set_attribute('myattr_name', $new_value);

But as I can see, there is no such method.

3
  • it's a simple or a variable product ?
    – mmm
    Mar 21, 2018 at 21:25
  • @mmm A simple one Mar 21, 2018 at 21:48
  • 2
    try with that : $product->set_props(["attributes" => ["myattr_name" => $new_value]]); $product->save();
    – mmm
    Mar 21, 2018 at 21:52

1 Answer 1

0

Finally I got it working with next code:

$product = wc_get_product($productId);
$attrName = 'my_attribute';
$attrValue = 'some value'

$attr = new WC_Product_Attribute();
$attr->set_name( $attrName );
$attr->set_options( [$attrValue] );
$attr->set_visible(1);
$attr->set_variation(1);
$attr->set_position(0);
$attr->set_id( 0 );
$attrs[$attrName] = $attr;
$product->set_attributes($attrs);
$product->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.