WordPress - Woocommerce wp_insert_post() 'post_category'

Wordpress - Woocommerce wp_insert_post() 'post_category'

我正在尝试导入具有 wp_insert_post() 功能的 woocommerce 产品,但我遇到了 'post_category' 的问题。我的密码是

$my_post = array(
  'post_content'   => $description, 
  'post_name'      =>  $product_name, 
  'post_title'     =>  $product_name, 
  'post_status'    => 'publish', 
  'post_type'      => 'product', 
  'post_author'    => 1, 
  'post_category'  =>  array(9,10)// ids from woocommerce categories
);

wp_insert_post( $my_post );

但是类别是空的。我试过 'product_cat' => array(9,10) 但没有再试过。谁能帮帮我?

尝试使用 wp_set_object_terms

$post_id = wp_insert_post( $my_post );
wp_set_object_terms($post_id, 9, 'product_cat', true);
wp_set_object_terms($post_id, 10, 'product_cat', true);

在导入产品之前,还要确保 product_cat 分类法中已经存在 ID 为 9 和 10 的术语。

你应该使用 slug 而不是 id:

wp_set_object_terms($post_id, get_term(9)->slug, 'product_cat', true);
wp_set_object_terms($post_id, get_term(16)->slug, 'product_cat', true);

如果您在此处放置新类别 slug,WordPress 将创建它,并将产品附加到该类别。