get_cat_ID()
Gets the category ID by the given name.
The function returns 0 if it fails to retrieve the identifier.
Uses: get_term_by()
No Hooks.
Returns
Int. Category ID or 0 if the category does not exist.
Usage
$cat_id = get_cat_ID( $cat_name );
- $cat_name(string) (required)
- Category name whose identifier needs to be retrieved. Default is General.
Examples
#1 Usage example
$cat_id = get_cat_ID( 'Category Name' );
#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>
#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. |
get_cat_ID() get cat ID code WP 6.9.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;
}