Support » Plugins » Hacks » Problem with wp_insert_post for custom post type – category is not associated

  • Hi there,

    (I’m re-posting this in the new “hacks” forum because my other post was in the wrong plugins forum. Thanks.)

    I set up a custom content type called “entries” 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 a code example:

    // Create post object
    $new_entry = array();
    $new_entry['post_title'] = esc_html($_POST['submit-title']);
    $new_entry['post_content'] = wp_kses($_POST['submit-text'], $allowed_html);
    $new_entry['post_status'] = 'publish';
    $new_entry['post_type'] = 'entries';
    $new_entry['post_author'] = $userID;
    $new_entry['post_category'] = array(6,7); // this is the line that doesn't work
    // Insert the post into the database
    $entry_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 are associated with the “entries” post type.)

    I also tried using wp_set_post_categories after I created the new post with wp_insert_post but that didn’t work either. This is the code I used for that:

    wp_set_post_categories( $entry_id, array(6,7) );

    Does anyone have any thoughts on what I’m doing wrong or other approaches they recommend?

    I’m using WordPress 3.0.1.


Viewing 4 replies - 1 through 4 (of 4 total)
  • I think post_category is an old parameter from when the post table use to hold data on a post’s categories, that no longer exists (or at least is no longer used), try wp_set_post_terms() for setting a post’s categories.

    i am having the same issue
    post_category doesn’t do anything

    wp_set_post_terms looks promising but how to use it??

    ok this seems to work

    $post_id = wp_insert_post( $my_post );
    	wp_set_post_terms($post_id,array(4, 6),'',true);

    but how do i add custom tags ??

    Im using wp_insert_post now to insert custum post types (with a custom hierarchical taxonomy)

    My solution:

    //first get the term (I used slug, but  you can aslo use 'name'), see:
    $term = get_term_by( 'slug', 'your custom term slug', 'your custom taxonomy' );
    //then get the term_id
    $term_id = $term->term_id;
    //Use 'tax_input' instead of 'post_category' and provide the term_id:
    'tax_input' => array( 'your taxonomy' => $term_id )

    now you can use wp_insert_post.

    Hope this helps somebody

    @wrk – word! Thanks for posting.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Problem with wp_insert_post for custom post type – category is not associated’ is closed to new replies.