这里提出的解决方案允许我轻松地为 WordPress 帖子创建“类别”:
//Check if category already exists
$cat_ID = get_cat_ID( $category );
//If it doesn't exist create new category
if($cat_ID == 0) {
$cat_name = array('cat_name' => $category);
wp_insert_category($cat_name);
}
//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);
// Create post object
$new_post = array(
'post_title' => $headline,
'post_content' => $body,
'post_excerpt' => $excerpt,
'post_date' => $date,
'post_date_gmt' => $date,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array($new_cat_ID)
);
// Insert the post into the database
wp_insert_post( $new_post );
但是,Woocommerce 无法识别这些类别。 Woocommerce 类别存储在其他地方。如何以编程方式创建 woocommerce 类别以及将其分配给新帖子的正确方法是什么?
Woocommerce 类别是 Product_cat 分类法中的术语。因此,要创建一个类别,您可以使用wp_insert_term:
wp_insert_term(
'New Category', // the term
'product_cat', // the taxonomy
array(
'description'=> 'Category description',
'slug' => 'new-category'
)
);
这将返回term_id
and term_taxonomy_id
, 像这样:array('term_id'=>12,'term_taxonomy_id'=>34))
然后,将新产品与类别关联起来就是简单地关联类别term_id
与产品帖子(产品是 Woocommerce 中的帖子)。首先,创建产品/帖子,然后使用wp_set_object_terms:
wp_set_object_terms( $post_id, $term_id, 'product_cat' );
顺便说一句,woocommerce 也提供了这些功能,可能更容易使用,但我在 wp cron 作业中遇到了 woocommerce 功能的问题,所以这些应该足以让你继续下去。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)