1

i have the code that can add a post in a custom post type but adding the category is not working.

$args = array(
    'post_title' => $title ,
    'post_status'   => 'publish',
    'post_type' => 'mypost' 
);

$post_id = wp_insert_post($args);

$category_ids = array(38,39);
wp_set_post_categories( $post_id, $category_ids, 'category');

2 Answers 2

2

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');
2
  • i already registered the post type and taxonomy, the problem is that the post that i created dynamically can't set category Commented Feb 8, 2018 at 11:43
  • Please, edit the question and provide that part of the code where you register the post type and the taxonomy.
    – cybmeta
    Commented Feb 8, 2018 at 12:13
0

As you are doing this for the custom post type, you need to use taxonomy. I will suggest you <?php wp_set_post_terms( $post_id, $terms, $taxonomy, $append ) ?> to use. please refer this link for the detailed use of the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.