PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to update product attribute taxonomy label name in WooCommerce

 May 09, 2022     attributes, php, product, woocommerce, wordpress     No comments   

Issue

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 ?


Solution

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.



Answered By - LoicTheAztec
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing