Php woocommerce中是否有函数以编程方式为产品创建类别?
我想附加一个类别的产品,并创建该类别,如果它不存在。这是我的密码。问题是wp_insert函数无法读取我传递的变量Php woocommerce中是否有函数以编程方式为产品创建类别?,php,woocommerce,Php,Woocommerce,我想附加一个类别的产品,并创建该类别,如果它不存在。这是我的密码。问题是wp_insert函数无法读取我传递的变量 $products = array( 'id' => 1, 'label' => 'tecno xyz', 'price' => 1250 , 'category' => array( 'id' => 1, 'label' => 'high tech') ); $categ
$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'
)
);
}
要检查产品类别是否存在,请不要使用
is_product_category
,因为该功能用于检查是否显示了特定的产品类别页面(请参阅,以获取每页上可用的标签列表)
产品类别是WooCommerce使用的自定义分类法(Product\u cat
),因此只需使用get\u 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.
}
}
嘿@Essy Telle!
wp\u insert\u term
函数无法读取您传递的变量是什么意思?在您的示例中,$category
将设置为high-tech
。你的意思是没有创建新的类别吗?另外,据我所知,is_product_category
仅检查您是否在某个产品类别页面上(请参阅以获取每页上可用的标签列表)。相反,您可能需要使用get_terms
(或类似工具)来获取现有产品类别。是@diegocolaantoni,类别未创建。无论类别是否存在,is_product_类别都返回布尔值。我已经通过将我的categry写为一个普通字符串而不是一个变量来测试它,is\u product\u category
函数是否只在相应的产品类别页面上返回true?如果您确定调用了wp\u insert\u term
(即$testCateg
为false),是否检查了函数是否返回了wp\u Error
对象?由于传递给它的变量,is\u product\u类别也不起作用。类别的名称是用普通字符串写的,一切正常!因此,如果我错了,请纠正我,wp\u insert\u term('high-tech','product\u cat')
有效,但在使用$category
变量时无效。必须有其他事情发生(例如,$category
从未设置)。你能发布完整的代码吗?