category_exists()WP 2.0.0

Checks if the specified category exists. If it does, it returns the ID of that category.

Categories are understood as terms of the taxonomy category, which are registered in WordPress by default and used in Posts.

This function is defined only in the admin area, so if called on the front end, it will result in an error:

Fatal error: Uncaught Error: Call to undefined function category_exists()

To make the category_exists() function work on the front end, you need to include the file:

require_once ABSPATH . 'wp-admin/includes/taxonomy.php';

With WP 6.0, the function works with caching and uses get_terms().

Before WP 6.0, this function performed a database query. get_term_by() can be used for the same purpose, except that it uses caching.

1 time — 0.0012069 sec (very slow) | 50000 times — 11.23 sec (slow)

No Hooks.

Returns

String|null. ID of the found category or null on failure.

Usage

category_exists( $cat_name, $parent );
$cat_name(string/integer) (required)
The category to check. You can specify the name, the alternative name (slug), or the ID.
$parent(string/integer)
ID of the parent category.
Default: null

Examples

2

#1 term_exists and category_exists

The function category_exists() is a wrapper for term_exists() to more easily check the default taxonomy terms category (categories, categories). The following two options do the same thing:

$cat_name = 'WordPress tags';

// Option 1
$id = category_exists( $cat_name );
print_r( $id ); //> 572

// Option 2
$id = term_exists( $cat_name, 'category' );

print_r( $id ); //> Array( [term_id] => 572 [term_taxonomy_id] => 572 )

if ( is_array( $id ) ) {
	$id = $id['term_id'];
}

print_r( $id ); //> 572
0

#2 Check the categories for existence bypassing the cache:

require_once ABSPATH . 'wp-admin/includes/taxonomy.php';

// Check the existence of the category
$tag = category_exists( 'WordPress' );

if( $tag ){
	var_dump( $tag ); // string(1) "3"
}

If the category exists, it will print its ID.

Notes

Changelog

Since 2.0.0 Introduced.

category_exists() code WP 6.9.1

function category_exists( $cat_name, $category_parent = null ) {
	$id = term_exists( $cat_name, 'category', $category_parent );
	if ( is_array( $id ) ) {
		$id = $id['term_id'];
	}
	return $id;
}