0

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

3 Answers 3

3

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);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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.
1
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.