且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式为新的 Woocommerce 产品创建设置类别?

更新时间:2023-01-09 14:34:29

Woocommerce 类别是 product_cat 分类法中的术语.因此,要创建类别,您可以使用 wp_insert_term:

Woocommerce categories are terms in the product_cat taxonomy. So, to create a category, you can use wp_insert_term:

wp_insert_term(
  'New Category', // the term 
  'product_cat', // the taxonomy
  array(
    'description'=> 'Category description',
    'slug' => 'new-category'
  )
);

这将返回 term_idterm_taxonomy_id,如下所示:array('term_id'=>12,'term_taxonomy_id'=>34))代码>

This returns the term_id and term_taxonomy_id, like this: array('term_id'=>12,'term_taxonomy_id'=>34))

然后,将新产品与类别相关联只是将类别 term_id 与产品帖子(产品是 Woocommerce 中的帖子)相关联.首先,创建产品/帖子,然后使用 wp_set_object_terms:

Then, associating a new product with the category is simply associating the category term_id with the product post (products are posts in Woocommerce). First, create the product/post and then use wp_set_object_terms:

wp_set_object_terms( $post_id, $term_id, 'product_cat' );

顺便说一句,woocommerce 也提供了这些功能,这可能更容易使用,但我遇到了 wp cron 作业中可用的 woocommerce 功能的问题,所以这些应该足以让你开始.

Btw, woocommerce offers functions for these too which might be easier to use but I have experienced issues with woocommerce functions available in wp cron jobs, so these should be enough to get you going.