The category_exists() WordPress PHP function checks whether a specific category exists in your WordPress database.
Usage
To use the category_exists() function, pass the category name as a parameter. You can also pass the parent category ID as an optional parameter.
$category_exists = category_exists('My Category', 1);
In the above example, the function will check if a category named ‘My Category’ exists under the parent category with the ID of 1. If the category exists, it will return the ID of the category. If not, it will return 0.
Parameters
- $cat_name (int|string) (Required) – The name of the category to check.
- $category_parent (int) (Optional) – The ID of the parent category. Default is null.
More information
See WordPress Developer Resources: category_exists()
Please note that this function is only available in the wp-admin area and will throw an error if used in the front end of your site. You should use term_exists() instead for frontend usage.
Examples
Check if a category exists
This example checks if the category ‘Travel’ exists.
$category_exists = category_exists('Travel'); if ($category_exists) { echo "The category exists"; } else { echo "The category does not exist"; }
Check if a sub-category exists
This example checks if the ‘Asia’ category exists under the ‘Travel’ parent category.
$parent_id = get_cat_ID('Travel'); $category_exists = category_exists('Asia', $parent_id); if ($category_exists) { echo "The sub-category exists"; } else { echo "The sub-category does not exist"; }
Creating a category if it doesn’t exist
This example creates a new category ‘Photography’ if it doesn’t already exist.
if (!category_exists('Photography')) { wp_create_category('Photography'); }
Checking multiple categories
This example checks the existence of multiple categories.
$categories = array('Travel', 'Food', 'Photography'); foreach ($categories as $category) { if (category_exists($category)) { echo "The category $category exists"; } else { echo "The category $category does not exist"; } }
Creating multiple categories if they don’t exist
This example creates multiple categories if they don’t exist.
$categories = array('Travel', 'Food', 'Photography'); foreach ($categories as $category) { if (!category_exists($category)) { wp_create_category($category); } }