![](/img/trans.png)
[英]Get a product from specific product attribute term name in WooCommerce
[英]Woocommerce is setting the Term ID rather than the Term name on Product Attribute
我想要做的是,如果用户选择一个分类属性,那么应该获取术语 id 并将其设置到选项中,但是这样做只是在属性变体中设置 id 而不是术语的名称
public static function create_product_attribute($product,$attribute_data){
$id = [];
function matchTerms($attribute,$types,$isTaxonomy){
$term_id = [];
($isTaxonomy == true) ? $options = (array) $attribute : $options = (array) $attribute->get_options();
foreach($options as $option){
($isTaxonomy == true) ? $name = $option->name : $name = get_term($option)->name;
foreach($types as $type){
if(strtolower($type) == strtolower($name)){
array_push($term_id,($isTaxonomy == true) ? $option->term_id : $option);
}
}
}
return $term_id;
}
foreach($attribute_data as $input_attribute){
$attributes = (array) $product->get_attributes();
$attribute = new KKART_Product_Attribute();
$attribute->set_name($input_attribute['name']);
if(strpos($input_attribute['name'],'pa_') !== false){
$terms = get_terms([
'taxonomy' => $input_attribute['name'],
'hide_empty' => false,
]);
$term_id = matchTerms($terms,$input_attribute['types'],$isTaxonomy = true);
// $terms = [];
// foreach($term_id as $term){
// array_push($terms,get_term($term)->name);
// }
}
(!empty($term_id)) ? $options = $term_id : $options = $input_attribute['types'];
$attribute->set_options($options);
$attribute->set_position( 1 );
$attribute->set_visible( 1 );
$attribute->set_variation( 1 );
$attributes[$attribute->get_name()] = $attribute;
$product->set_attributes($attributes);
array_push($id,$product->save());
}
return $id;
}
`$attribute_data 中的数据为:
[
{"name":"Color","types":["red"]},
{"name":"pa_material","types":["Type"]}
]
事实证明,当 term_id 在后端传递时它工作正常,但是当您在属性产品部分检查它时,它只显示术语 id 而不是名称,您只需要保存属性并让它重新加载,但即使如果您不保存它并保持原样,它将对最终用户正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.