首页 > 解决方案 > 如何在 WooCommerce 中更新产品属性分类标签名称

问题描述

我有一个属于分类的属性,我需要更新属性标签。这是我到目前为止所做的

 $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();
  }

如果我读回产品属性,标签没有更新(读取旧标签),我需要更新属性标签并将其保存到数据库中,以便当值被读回时,它反映了新更新的标签。

我错过了什么?

标签: phpwordpresswoocommerceattributesproduct

解决方案


要更改/更新产品属性分类数据,您需要使用wc_update_attribute()function,因此在您的代码中,更改产品属性标签名称:

$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,
            ) );
        }
    }
}

测试和工作。


推荐阅读