2014-11-01 45 views
4

这里提出的解决方案可以让我轻松了WordPress邮寄打造“分类”:如何以编程方式设置新Woocommerce产品创建的类别?

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

回答

11

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_idterm_taxonomy_id,像这样:array('term_id'=>12,'term_taxonomy_id'=>34))

然后,关联与A类新产品被简单地类别term_id与之为伍产品帖子(产品是Woocommerce中的帖子)。首先,创建产品/后,然后使用wp_set_object_terms

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

顺便说一句,woocommerce提供功能这些也可能是更容易使用,但我已经在WP cron作业提供woocommerce功能遇到的问题,所以这些应该足以让你走了。

+0

如何添加'product_cat'本身? – 2017-05-19 18:53:56

1

您可以加载一个产品:

$product = wc_get_product($id); 

然后设置类别:

$product->set_category_ids([ 300, 400 ]); 

最后你应该保存,因为处理性能的操作使用道具setter方法,其中存储在变化稍后保存到数据库的数组:

$product->save(); 

有关更多信息,请参阅API文档信息:https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

最好使用WC提供的功能来提供向前和向后的兼容性。

相关问题