0

I am trying to add a new post using the function wp_inser_post in one of my existing categories, I've created a new taxonomy named categorie and in that taxonomy i have a few categories, and I am not able to find a solution, the post is being added but no category is selected.

  $title =  $_POST['postTitle'];
  $description = $_POST['postContent'];  

  $new_post = array(
    'post_title' => esc_attr(strip_tags($title)),
    'post_content' => esc_attr(strip_tags($description)),
    'post_type' => 'proiecte',
    'post_status' => 'publish',
    'post_category' =>  array(17,16),
    'taxonomy'      => 'categorie'
  );

  $post_id = wp_insert_post($new_post);

2 Answers 2

1

post_category is only for Core Categories. Use tax_input instead:

$new_post = array( 
    'post_title' => esc_attr(strip_tags($title)),
    'post_content' => esc_attr(strip_tags($description)),
    'post_type' => 'proiecte',
    'post_status' => 'publish',
    'tax_input' => array(
        'categorie' => array(17,16)
    )
);
$post_id = wp_insert_post($new_post);

It may be clearer to other developers, and yourself in the future, if you use something other than categorie - perhaps projecte_category - just so it's clearer you're using a custom taxonomy and not misspelling Category.

1
  • Thank you! worked like a charm! i will keep in mind your advice in the project to come. Have a nice day ! Commented May 5, 2018 at 8:56
0

You can use WordPress's wp_set_object_terms to do this. You can call this function after wp_insert_post call.

$post_id = wp_insert_post($new_post);

wp_set_object_terms( $post_id, 'term', 'categorie' );

You can pass set multiple terms by passing array of term. Ceck this for more.https://developer.wordpress.org/reference/functions/wp_set_object_terms/

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.