Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wordpress 如何以编程方式设置新产品创建的类别?_Wordpress_Woocommerce - Fatal编程技术网

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

Wordpress 如何以编程方式设置新产品创建的类别?,wordpress,woocommerce,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

这里介绍的解决方案使我能够轻松地为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 );

然而,Woocommerce不承认这些类别。电子商务类别存储在其他地方。如何以编程方式为woocommerce创建类别,以及将其分配给新帖子的正确方式是什么?

woocommerce类别是产品分类法中的术语。因此,要创建类别,可以使用:

这将返回
术语id
术语分类法id
,如下:
数组('term\u id'=>12,'term\u分类法id'=>34))

然后,将新产品与类别关联只是将类别
term\u id
与产品帖子关联(产品是Woocommerce中的帖子)。首先,创建产品/帖子,然后使用:


顺便说一句,woocommerce也提供了这些功能,这些功能可能更易于使用,但我在wp cron作业中遇到了woocommerce功能的问题,因此这些功能应该足以让您继续使用。

您可以加载一个产品:

$product = wc_get_product($id);
然后设置类别:

$product->set_category_ids([ 300, 400 ] );
最后应该保存,因为处理属性的操作使用prop setter方法,这些方法将更改存储在数组中,以便稍后保存到DB:

$product->save();
有关更多信息,请参阅API文档:


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

如何添加“product_cat”本身?@kroky如何根据产品类别slug获取术语id?(由于id可以更改,但slug通常是相同的)@Amjad您可以使用
get\u term\u by('slug','the category slug','product\u cat')
-查看文档,这些文档非常有用:您救了我的命
$product->set_category_ids([ 300, 400 ] );
$product->save();