2

How would be the array, to insert a post category and subcategory?

Thanks.

3

2 Answers 2

4

The argument description in the Codex entry for wp_insert_post() has exactly what you need (reformatted).

'post_category'  => [ array(<category id>, <...>) ] 
//post_category no longer exists, try wp_set_post_terms() for setting a post's categories

So, per the Codex. Use wp_set_post_terms().

wp_set_post_terms( $post_id, array( 1, 2, 3), 'category', true );

For custom taxonomies:

'tax_input' => array( 
  'taxonomy_name' => array( 
    'term', 
    'term2', 
    'term3' 
  ) 
); // support for custom taxonomies. 

Just change the taxonomy name to the one you want and replace the term placeholders with the category slugs you want.

The Codex weakly implies that you can no longer set the category via wp_insert_post(). However, while I haven't tested it I would not be surprised if that tax_input argument also works for the category taxonomy, like so:

'tax_input' => array( 
  'category' => array( 
    'a', 
    'b', 
    'c' 
  ) 
);
2
  • 2
    I'm confused. Are you saying that post_category in wp_insert_post does work, or does it not?
    – Flimm
    Commented Aug 29, 2019 at 15:43
  • 2
    when you use post_category you just need to send an array of post category IDs to it.
    – Robbiegod
    Commented Jul 27, 2020 at 15:06
1

Worked for me with wp_set_object_terms()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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