I set up a custom content type called “photo” which is working fine. Now I’m inserting posts with that content type using wp_insert_post() and am encountering a problem adding a category. These are hierarchical categories that I associated with the post type and can set in the admin area, but I try to associate them using PHP code, it doesn’t work.
Here is the code snippet:
$new_entry = array();
$new_entry['post_title'] = $_POST['submit-title'];
$new_entry['post_content'] = '';
$new_entry['post_status'] = 'pending';
$new_entry['post_type'] = 'photo';
$new_entry['post_author'] = $userID;
$new_entry['post_category'] = array(6,7); // this is the line that doesn't work
$new_entry['tags_input'] = array('nature','people','fun'); // this also doesn't work
// Insert the post into the database
$post_id = wp_insert_post( $new_entry );
This all works and the custom post is inserted and shows up as expected, but it doesn’t have any categories assigned to it. (Categories 6 and 7 are categories that should be associated with the “photo” post type). More than that the tags are also not created and associated with this post.
Does anyone have any thoughts on what I’m doing wrong or other approaches they recommend?
There is a function for that, it is called wp_set_object_terms(). http://codex.wordpress.org/Function_Reference/wp_set_object_terms
eg:
you can use the same function to add tags