通过自定义前端表单设置Woocommerce产品标签和类别


Setting Woocommerce Product Tags and Categories via Custom Frontend Form

我正在构建一个表单,供用户使用wp_insert_postupdate_post_meta通过我的网站前端创建产品。

在尝试设置产品类别和标签时会出现问题。Wooccommerce在这方面似乎没有使用标准的Wordpress分类法。有人有这方面的经验吗?Wooccommerce似乎在某些地方使用product_tags。有没有类似Wordpress的功能来创建它们?

下面是我正在做的事情的一个片段。谢谢

$post = array(
 'ID' => '',
 'post_content' => $_POST['post_content'],
 'post_title' => $_POST['post_title'],
 'post_status' => 'draft',
 'post_type' => 'product',
 'post_author' => $user_id,
);
$newListing = wp_insert_post($post, $wp_error);
//SET META
update_post_meta($newListing, '_stock_status', 'instock', true);
update_post_meta($newListing, '_visibility', 'visible', true);
update_post_meta($newListing, '_price', $_POST['_regular_price'], true);
//SET CATEGORIES - **NOT WORKING**
wp_set_post_categories($newListing, $categories);
//SET THE TAGS **NOT WORKING**
wp_set_post_tags($newListing, $tags, true);

发现内置的Wordpress函数wp_set_object_terms可以很容易地处理这一问题。

以下是一些例子:

//SET THE PRODUCT CATEGORIES
wp_set_object_terms($productID, array('Cat Name 1', 'Cat Name 2'), 'product_cat');
//SET THE PRODUCT TAGS
wp_set_object_terms($productID, array('tag1','tag2','tag3'), 'product_tag');