我想为产品附加一个类别,如果该类别不存在,则创建该类别。有我的代码。问题是 wp_insert 函数无法读取我传递的变量
$products = array(
'id' => 1,
'label' => 'tecno xyz',
'price' => 1250 ,
'category' => array(
'id' => 1,
'label' => 'high tech')
);
$category = $products['category']['label'];
$testCateg = is_product_category([$term = $category]);
if (!$testCateg) {
wp_insert_term(
$category, // the term
'product_cat', // the taxonomy
array(
'description'=> 'New New Category description for testing purpose'
//'slug' => 'new-category'
)
);
}
答案 0 :(得分:0)
要检查产品类别是否存在,请不要使用 is_product_category
,因为该函数用于检查某个产品类别页面是否显示(请参阅 WooCommerce conditional tags 以获取每页)。
产品类别是 WooCommerce 使用的自定义分类法 (product_cat
),因此只需使用 get_terms
即可检索现有产品类别。例如,如果新类别不存在,则添加新类别可以这样实现:
function add_product_category() {
$new_product = array(
'id' => 1,
'label' => 'tecno xyz',
'price' => 1250,
'category' => array(
'id' => 1,
'label' => 'high tech',
),
);
$category = $new_product['category']['label'];
$args = array(
'hide_empty' => false,
);
$product_categories = get_terms( 'product_cat', $args );
foreach ( $product_categories as $key => $product_category ) {
if ( $product_category->name === $category ) {
return;
}
}
$term = wp_insert_term(
$category,
'product_cat',
array(
'description' => 'New Category description for testing purpose',
),
);
if ( is_wp_error( $term ) ) {
// do something with error.
}
}