如何在WooCommerce中更新产品属性分类标签名称

时间:2020-08-26 09:05:01

标签: php wordpress woocommerce attributes product

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

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

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

我想念什么?

1 个答案:

答案 0 :(得分:1)

要更改/更新产品属性分类法数据,您需要使用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,
            ) );
        }
    }
}

经过测试可以正常工作。

相关问题