Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Woocommerce Product Tags and Categories via Custom Frontend Form

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);
like image 467
user1199981 Avatar asked Apr 17 '14 21:04

user1199981


1 Answers

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');
like image 52
user1199981 Avatar answered Oct 13 '22 07:10

user1199981