0
votes

I really hope someone can help me with this problem asap.

Ok so I am building a costum script for users to publish a new product, I have everything working and inserting successfully (Event the photo) but just cant seem to find anywhere what code should be used to update the post category, as it is not a normal category because it has the taxonomy of "product_cat" (woocommerce product category).

Any ideas?

Non of the following work: ($term_id is the term_id that relates to the "product_cat" of a certain product)

    wp_set_post_terms($post_id, array($term_id), "product_cat");
    wp_set_post_terms($post_id, (int)$term_id, "product_cat");
    update_post_meta($post_id,'product_cat',$term_id);
    

I have tried others but they just dont seem to do anything at all, some functions even create a new category with the id...

2

2 Answers

3
votes

You can use:
wp_set_post_terms( int $post_id, string|array $tags = '', string $taxonomy = 'post_tag', bool $append = false )

Parameters:

$post_id (int) (Optional) The Post ID. Does not default to the ID of the global $post.

$tags (string|array) (Optional) An array of terms to set for the post, or a string of terms separated by commas. Hierarchical taxonomies must always pass IDs rather than names so that children with the same names but different parents aren't confused. Default value: ''

$taxonomy (string) (Optional) Taxonomy name.

Default value: 'post_tag'

$append (bool) (Optional) If true, don't delete existing terms, just add on. If false, replace the terms with the new terms.

Default value: false

Read more about it here: https://developer.wordpress.org/reference/functions/wp_set_post_terms/

0
votes

Try with wp_insert_term:

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