2014-11-01 132 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提供的功能來提供向前和向後的兼容性。

相關問題