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?
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?
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 ;)
$post_id
returning a post id? If there's a problem creating the post, that variable could also be a wp_error. – MikeNGarrett Commented Feb 20, 2019 at 15:24wp_set_post_categories
is unnecessary, passingpost_category
as a parameter should be enough on its own. Where is$categories_id
coming from? – Tom J Nowell ♦ Commented Feb 20, 2019 at 15:34test
post type actually support categories? If you don't declare that it supports them, you can't add them – Tom J Nowell ♦ Commented Feb 20, 2019 at 15:35