get_cat_ID()WP 1.0.0

Retrieve the ID of a category from its name.

No Hooks.

Return

Int. Category ID on success, 0 if the category doesn't exist.

Usage

get_cat_ID( $cat_name ) // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid;
$cat_name(string) (required)
Category name.

Examples

1

#1 Usage example

$cat_id = get_cat_ID( 'Category Name' );
0

#2 Use category id

Useful for a function such as category_description() that requires a category’s ID:

<?php $cat_id = get_cat_ID ( 'Category Name', 'textdomain' ); ?>

<p>The 'Category Name' description is: <?php echo category_description( $cat_id ) ?></p>
-1

#3 Get posts from specified category

An example of using this function to retrieve posts from a specific category using query_posts():

$category_id = get_cat_ID('Category name');

$q = 'cat=' . $category_id;

query_posts( $q );

if( have_posts() ){

	while( have_posts() ){
		the_post();

		the_content();
	}
}

wp_reset_query();

Changelog

Since 1.0.0 Introduced.

Code of get_cat_ID() WP 6.0.1

function get_cat_ID( $cat_name ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
	$cat = get_term_by( 'name', $cat_name, 'category' );

	if ( $cat ) {
		return $cat->term_id;
	}

	return 0;
}