如何在woocommerce产品中添加类别和子类别?

I'm creating a plugin to add a product to woocommerce and $th1 is the category , $sth1 is the subcategory.

I tried this but it doesn't work:

 wp_set_object_terms( $post_id,$th1->$sth1,'product_cat');

I want add the product to the category and the subcategory. how can i do this, please?

Providing you have the term_id's for your categories (i.e with get_term_by), you can do:

wp_set_object_terms($post_id, [$category->term_id, $sub_category->term_id], 'product_cat');

You need to add product ID to table term_relationships. For this, you will need to have "term_taxonomy_id" from "term_taxonomy" table.

So here, in term_relationships object_id = product ID AND term_taxonomy_id found from term_taxonomy table.

You can assign any category/subcategory to product this way.