How to set category to product woocommerce

After some trial and error I solved it the following way:

// Creates woocommerce product 
$product = array(
    'post_title'    => $name,
    'post_content'  => '',
    'post_status'   => 'publish',
    'post_author'   => $current_user->ID,
    'post_type'     =>'product'
);

// Insert the post into the database
$product_ID = wp_insert_post($product);

// Gets term object from Tree in the database. 
$term = get_term_by('name', 'Tree', 'product_cat');

wp_set_object_terms($product_ID, $term->term_id, 'product_cat');

reference for more information:

  • How to programatically set the category for a new Woocommerce Product Creation?
  • http://codex.wordpress.org/Function_Reference/get_term_by
  • https://wordpress.stackexchange.com/questions/16394/how-to-get-a-taxonomy-term-name-by-the-slug

If you need multiple categories, just pass an array:

$categories = [ 'Some Category', 'Some other Category' ];

// Overwrite any existing term
wp_set_object_terms( $product_id, $categories, 'product_cat' );


// Or, set last argument to true to append to existing terms
wp_set_object_terms( $product_id, $categories, 'product_cat', true );