如何以编程方式为新的 Woocommerce 产品创建设置类别? [英] How to programatically set the category for a new Woocommerce Product Creation?

查看:27
本文介绍了如何以编程方式为新的 Woocommerce 产品创建设置类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处提供的解决方案让我可以轻松地为 wordpress 帖子创建类别":

The solution presented here allows me to easily create "Categories" for a wordpress post:

//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 创建类别以及将其分配给新帖子的正确方法是什么?

However, Woocommerce doesn't recognise these categories. Woocommerce categories are stored somewhere else. How can I programmatically create the categories for woocommerce and what is the correct way to assign it to a new post?

推荐答案

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.

这篇关于如何以编程方式为新的 Woocommerce 产品创建设置类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆