0

I tried to assign array of categories to custom post type on creation, so I wrote the following code:

$post_id = wp_insert_post( array(
        'post_content' => '',
        'post_name' => $title_slug,
        'post_title' => $title_slug,
        'post_status' => 'publish',
        'post_type' => 'test',
        'post_author' => 'me',
        'post_excerpt' => '',
    //  'post_date' => $date,
        'post_category' => $categories_id,
    //  'tags_input' => array($tags)
    ));
    //print_r($post_categories );
    print_r($categories_id);
    wp_set_post_categories( $post_id, $categories_id) ;

But it doesn't work no category was affected to the custom post even if the print_r($categories_id) return the following array Array ( [0] => 51 [1] => 52 [2] => 53 [3] => 54 [4] => 55 [5] => 54 ) which is the list of category id.

Any ideas?

  • Is the $post_id returning a post id? If there's a problem creating the post, that variable could also be a wp_error. – MikeNGarrett Feb 20 at 15:24
  • Hi, the post is created well , with the title defined , only categories are not affected to the custom post created. – alpha.romeo Feb 20 at 15:27
  • Your call to wp_set_post_categories is unnecessary, passing post_category as a parameter should be enough on its own. Where is $categories_id coming from? – Tom J Nowell Feb 20 at 15:34
  • Also, does your test post type actually support categories? If you don't declare that it supports them, you can't add them – Tom J Nowell Feb 20 at 15:35
  • my post type support category , the meta box category is visible in the right of custom post edit page , and the $categories_id array is comming from list of wp_create_category('categorie_name') command – alpha.romeo Feb 20 at 15:39
0

Use the tax_input argument like this:

$categories = array(51,52,53,54,55);
$post_id = wp_insert_post( array(
        'post_content' => '',
        'post_name' => $title_slug,
        'post_title' => $title_slug,
        'post_status' => 'publish',
        'post_type' => 'test',
        'post_author' => 'me',
        'post_excerpt' => '',
    //  'post_date' => $date,
        'post_category' => $categories_id,
    //  'tags_input' => array($tags),
        'tax_input' => array(
                         'category' => $categories
                       );
    ));

Happy Coding ;)

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.