tags:

views:

52

answers:

3

How can I check if a category exists, and if exists, return the ID; if not, create the category?

+3  A: 

Use Wordpress is_category(), get_cat_ID() and wp_create_category() method.

<?php
  $CategoryName = "books";
  if(is_category($CategoryName))
        $categoryID = get_cat_ID($CategoryName);
  else
        $categoryID = wp_create_category($CategoryName);
?>
shamittomar
+1  A: 

See wp_create_category().

include( "../../wordpress/wp-config.php" );
include( "../../wordpress/wp-admin/includes/taxonomy.php" );

$cat_id = wp_create_category( "TESTINGLOL" );
echo "created = {$cat_id}\n";
echo "returned = " . get_cat_ID( "TESTINGLOL" );

Output should go like:

created = 37450 returned = 37450

Note that this isn't very efficient, but, does the job.

pp19dd
Note that this method doesn't require checking whether the category already exists - if it does, wp_create_category() will simply return its cat ID.
pp19dd
+1  A: 
create_category_if_not_exist($category_name, $echo = true) {
    $id = wp_insert_term( $category_name, 'category');
    if ( $echo ) return $id;
    return $id;
}

Nice all in one function for doing the trick. $category_name would need to be the category slug though.

wp_insert_term() takes care of checking if the category already exists in the database. It will return the $id of the category if it exists and will return the $id of the newly created category if it doesn't pre-exist.

Darren