cod*_*ama 5 wordpress woocommerce
这里介绍的解决方案允许我轻松创建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 );
Run Code Online (Sandbox Code Playgroud)
但是,Woocommerce不承认这些类别.Woocommerce类别存储在其他地方.如何以编程方式为woocommerce创建类别以及将其分配给新帖子的正确方法是什么?
kro*_*oky 15
Woocommerce类别是product_cat分类中的术语.因此,要创建一个类别,您可以使用wp_insert_term:
wp_insert_term(
'New Category', // the term
'product_cat', // the taxonomy
array(
'description'=> 'Category description',
'slug' => 'new-category'
)
);
Run Code Online (Sandbox Code Playgroud)
这将返回term_id和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' );
Run Code Online (Sandbox Code Playgroud)
顺便说一句,woocommerce也提供了这些功能,可能更容易使用,但我遇到过wp cron作业中可用的woocommerce功能的问题,所以这些应该足以让你前进.
您可以加载产品:
$product = wc_get_product($id);
Run Code Online (Sandbox Code Playgroud)
然后设置类别:
$product->set_category_ids([ 300, 400 ] );
Run Code Online (Sandbox Code Playgroud)
最后,您应该保存,因为处理属性的操作使用prop setter方法,该方法将更改存储在数组中,以便稍后保存到DB:
$product->save();
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参见API文档:https : //docs.woocommerce.com/wc-apidocs/class-WC_Product.html
最好使用WC提供的功能来实现向后和向前兼容性。