category_exists()WP 2.0.0

Checks whether a category exists.

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

No Hooks.

Return

String|null. Returns the category ID as a numeric string if the pairing exists, null if not.

Usage

category_exists( $cat_name, $category_parent );
$cat_name(int|string) (required)
Category name.
$category_parent(int)
ID of parent category.
Default: null

Examples

0

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

0

#2 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

Notes

Changelog

Since 2.0.0 Introduced.

category_exists() code WP 6.1.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;
}