I tried to add a category based on a post as seen on this link:
How we add new categories by wp_insert_post

Here, I added 'post_category' and default category IDs in an array as shown below:

$my_post = array(
    'post_title'    => 'test',
    'post_content'  => 'hello',
    'post_status'   => 'publish',
    'post_author'   =>  1,
    'post_type'     => 'product',
    'post_category' => array(2,3,4,5)
 $post_id = wp_insert_post($my_post);

All of the fields above have been added, except for the post_category. I wanted to add more than one category per product, and what I am using is an array.

What is probably the problem here?


You can use wp_set_object_terms() to assign taxonomy terms to a post.

wp_set_object_terms($post_id, $terms, $taxonomy, true);

Where $terms - A single term slug, single term id, or array of either term slugs or ids. Will replace all existing related terms in this taxonomy.

See documentation: https://codex.wordpress.org/Function_Reference/wp_set_object_terms


In your case, it will look like:

wp_set_object_terms($post_id, array(2,3,4,5), 'category', true);

Please check for any syntax error.

| improve this answer | |
  • what should I put in a $terms and $taxonomy so that I can insert category posts in an array? – smzapp Apr 19 '17 at 6:58
  • Check the edit, use proper category ids. – Aniruddha Gawade Apr 19 '17 at 7:02
  • I tried this but didn't work.. :( – smzapp Apr 19 '17 at 7:18
  • Print and check what the function returns. Check documentation for return types. – Aniruddha Gawade Apr 19 '17 at 7:23
  • print_r(wp_set_object_terms($post_id, $terms['category'], 'category')); but this returns to category values.., I tried the sku and it's working.. update_post_meta() – smzapp Apr 19 '17 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.