11

is it possible to add a category to a woocommerce post?

I am creating my products as follows:

// 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);

I have a category called "Tree" where I have to add the above product to. I have tried the following but without succes. Is there some special way to add a category?

wp_set_object_terms($productID, array('Tree'), 'product_cat');
user1213904
  • 1,830
  • 4
  • 23
  • 39

2 Answers2

21

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:

user1213904
  • 1,830
  • 4
  • 23
  • 39
  • 1
    If you get $termID in different mode, and it's a string, WP creates a new term with name of the number, so add `(int)` before second arg: `wp_set_object_terms($product_ID, (int)$term_id, 'product_cat');` – Harkály Gergő Feb 15 '19 at 11:29
5

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 );
Lucas Bustamante
  • 15,821
  • 7
  • 92
  • 86