Reputation: 3485
I have a an attribute that is a taxonomy, I need to update the attribute label. Here is what i've done iso far
$args = array(
'category' => array('chinese'),
'orderby' => 'name',
);
$products = wc_get_products($args);
foreach($products as $product)
{
$attribute = $product->get_attributes();
foreach($attribute as $attributeItem)
{
if($attributeItem->is_taxonomy())
{
$attributeItem->get_taxonomy_object()->attribute_label = "new-label"; // set new label
}
}
$product->set_attributes($attribute);
$product-save();
}
If i read back the product attribute, the label is not updated (reading the old label), i need to update the attribute label and save it to the database so that when the value gets read back, it reflects the newly updated label.
What am i missing ?
Upvotes: 1
Views: 1543
Reputation: 253784
To change/update product attribute taxonomy data you need to use wc_update_attribute()
function, so in your code, to change the product attribute label name:
$products = wc_get_products( array('category' => 't-shirts', 'orderby' => 'name') );
// Loop through queried products
foreach($products as $product) {
// Loop through product attributes
foreach( $product->get_attributes() as $attribute ) {
if( $attribute->is_taxonomy() ) {
$attribute_id = $attribute->get_id(); // Get attribute Id
$attribute_data = wc_get_attribute( $attribute_id ); // Get attribute data from the attribute Id
// Update the product attribute with a new taxonomy label name
wc_update_attribute( $attribute_id, array(
'name' => 'New label', // <== == == Here set the taxonomy label name
'slug' => $attribute_data->slug,
'type' => $attribute_data->type,
'order_by' => $attribute_data->order_by,
'has_archives' => $attribute_data->has_archives,
) );
}
}
}
Tested and works.
Upvotes: 3