1

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

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

1

2 Answers 2

2
$id = wp_create_category('My category name');

By above function category created & categary id is returned.

If the category already exists, it is not duplicated. The ID of the original existing category is returned without error.

You can use $id as category id.

Reference

http://codex.wordpress.org/Function_Reference/wp_create_category

2
  • When i use this funtion, my all page stuck and display nothing.
    – Adi
    Commented Mar 28, 2013 at 12:52
  • wp_create-category is a valid function but is a "thin wrapper" around the wp_insert_category function, so it isn't substantially different from what the OP has tried.
    – s_ha_dum
    Commented Mar 28, 2013 at 13:09
0

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.

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.