How to programatically set the category for a new Woocommerce Product Creation? How to programatically set the category for a new Woocommerce Product Creation? wordpress wordpress

How to programatically set the category for a new Woocommerce Product Creation?


Woocommerce categories are terms in the product_cat taxonomy. So, to create a category, you can use wp_insert_term:

wp_insert_term(  'New Category', // the term   'product_cat', // the taxonomy  array(    'description'=> 'Category description',    'slug' => 'new-category'  ));

This returns the term_id and term_taxonomy_id, like this: array('term_id'=>12,'term_taxonomy_id'=>34))

Then, associating a new product with the category is simply associating the category term_id with the product post (products are posts in Woocommerce). First, create the product/post and then use wp_set_object_terms:

wp_set_object_terms( $post_id, $term_id, 'product_cat' );

Btw, woocommerce offers functions for these too which might be easier to use but I have experienced issues with woocommerce functions available in wp cron jobs, so these should be enough to get you going.


You can load a product:

$product = wc_get_product($id);

Then set categories:

$product->set_category_ids([ 300, 400 ] );

Finally you're supposed to save, because operations dealing with properties use prop setter methods, which store changes in an array for saving to the DB later:

$product->save();

See the API Documentation for more information: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

It is better to use WC-provided functions for backwards and forwards compatibility.