You need to register the custom post type with support for the category
taxonomy:
add_action('init', 'cyb_register_post_type');
function cyb_register_post_type() {
$args = array(
// All the other args
'taxonomies' => array( 'category' ),
);
register_post_type( 'my_post_type', $args );
}
Then you can set relationships between the custom post type and the categoy
taxonomy as you was doing, but you have to correct the code.
From this:
wp_set_post_categories( $post_id, $category_ids, 'category');
To this (previous categories are deleted and replaced by the new categories):
wp_set_post_categories( $post_id, $category_ids );
// The above line is equivalent to
// wp_set_post_categories( $post_id, $category_ids, false );
// or
// wp_set_post_terms( $post_id, $category_ids, 'category', false );
Or to (previous categories are not deleted, new categories are appended):
wp_set_post_categories( $post_id, $category_ids, true );
You can also register a custom taxonomy and use it for your custom post type:
add_action('init', 'cyb_register_post_type_and_taxonomy');
function cyb_register_post_type_and_taxonomy() {
$post_type_args = array(
// All the other args
'taxonomies' => array( 'my_custom_taxonomy' ),
);
register_post_type( 'my_post_type', $post_type_args );
$taxonomy_args = array(
// Arguments for the custom taxonomy
// See https://developer.wordpress.org/reference/functions/register_taxonomy/
);
register_taxonomy( 'my_custom_taxonomy', 'my_post_type', $args );
}
And then use wp_set_post_terms()
, not wp_set_post_categories()
:
wp_set_post_terms( $post_id, $category_ids, 'my_custom_taxonomy');