php - 如何在 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();
}
如果我读回产品属性,标签没有更新(读取旧标签),我需要更新属性标签并将其保存到数据库中,以便当值被读回时,它反映了新更新的标签。
我错过了什么?
解决方案
要更改/更新产品属性分类数据,您需要使用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,
) );
}
}
}
测试和工作。
推荐阅读
- yosys - ABC 综合 - read_liberty
- python - Python:如何使用 Django 将 Python 函数分配给 HTML 按钮
- constraints - 从 OptaPlanner 7.46.0 切换到 8.0.0 时,约束流中断
- r - 模糊连接错误:小标题中的所有列都必须是向量
- javascript - 这个异步等待代码(javascript)有什么问题?
- laravel - 更好的开源地图,比如 laravel 的谷歌地图?
- android - 在 React Native 上无延迟地渲染许多图表
- python - 在每个端口上停止 Python localhost 服务器
- javascript - DOM 事件 attributeModified/attributeRemoved/characterDataModified... 未触发
- javascript - html5音频播放器通过innerhtml问题刷新了preventdefault