How we add new categories by wp_insert_post

I am using fornt end form submission now i want to add new category and before adding this category i want to check whether it exist or not, if yes then simple add to that category otherwise add new one. So the in codex they said if you have to add catogory just use the

wp_set_post_terms();

and there is one more function to add this which is

Read More
wp_set_object_terms();

and there is one more way of adding category is

wp_insert_category($cat_name);

so there is confussion in both how they work and which one i chose form them. I have name of category so can i use it now. There is code how to add them but they are not working for me.

//Check if category already exists
$cat_ID = get_cat_ID( $category );

//If it doesn't exist create new category
if($cat_ID == 0) {
$cat_name = array('cat_name' => $category);
wp_insert_category($cat_name);
}

//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);

// Create post object
$new_post = array(
'post_title' => $headline,
'post_content' => $body,
'post_date' => $date,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array($new_cat_ID)
);

So any solution for that. Thanks

Related posts

Leave a Reply

2 comments

  1. WordPress provide a way to define other object than just Posts : this is called custom post types. And each custom post type can have its own taxonomies, an entry in a specific taxonomy being call a “term”. The default taxonomy for the default post type is a “category”.

    So wp_set_post_terms can be used to set a category to a post, but also to set a term in another taxonomy. And wp_set_object_terms is even more generic : you can use it to set a term in any taxonomy for any post type. The more specialized function you should use to set a category to a post is wp_set_post_categories. wp_set_post_categories uses wp_set_post_terms, which uses wp_set_object_terms. Does that makes sense for you ?

    wp_insert_category does a different job : it creates a new category in the list of available categories, but it does not set this category for a particular post.