Using ‘tax_input’ with wp_insert_post() and nothing happens

While working on a client site certain functionality called for inserting a post into a custom post type, using a custom taxonomy, via input from a user on the front-end. Luckily for us, WordPress has provided us with the handy dandy wp_insert_post() function. It’s pretty straight forward, you pass the $post array as the argument and voila. Done and done, right? Nope.

If you are using the ‘tax_input’ element as I was, your taxonomy is not being added. It turns out that ‘tax_input’ does not work if a user does not have the capabilities to work with a custom taxonomy. To solve this you can simply use wp_set_object_terms() immediately after the post is inserted passing the $post_id and terms you would like to add.

Tl;dr: Don’t use wp_insert_post(), use wp_set_object_terms() once the post has been inserted.

Protip: If you use wp_set_object_terms() and the taxonomy does not exist, WordPress will automatically create it and sanitize the slug.

, ,

No comments yet.

Leave a Reply