Reputation: 428
I am building a form for users to create a product via the frontend of my site using wp_insert_post
and update_post_meta
.
The problem arises when trying to set the product categories and tags. It seems Woocommerce doesn't use standard Wordpress taxonomies in this regard. Anyone have any experience with this? It seems Woocommerce uses product_tags
in some places. Is there a function to create them similar to Wordpress?
Below is a snippet of what I am doing. Thanks!
$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);
Upvotes: 13
Views: 10568
Reputation: 61
use wp_set_object_terms() function and pass array of term_id
wp_set_object_terms($product_id, array(1,8,10), 'product_cat');
wp_set_object_terms($product_id, array(1,8,10), 'product_tag');
Upvotes: 1
Reputation: 428
Found out the built-in Wordpress function wp_set_object_terms
will handle this quite easily.
Below are some examples:
//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');
Upvotes: 20