get_cat_ID()
Retrieve the ID of a category from its name.
Uses: get_term_by()
No Hooks.
Return
Int
. Category ID on success, 0 if the category doesn't exist.
Usage
get_cat_ID( $cat_name );
- $cat_name(string) (required)
- Category name.
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.7.2
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; }