Using WordPress ‘get_cat_ID()’ PHP function

The get_cat_ID() WordPress PHP function retrieves the ID of a category from its name.

Usage

$cat_id = get_cat_ID('Category Name');

Parameters

  • $cat_name (string) – Required. The name of the category for which you want to retrieve the ID.

More information

See WordPress Developer Resources: get_cat_ID()

Examples

Display Category Description

Retrieve the ID of the ‘Travel’ category and display its description:

$cat_id = get_cat_ID('Travel');
echo '<p>The Travel category description is: ' . category_description($cat_id) . '</p>';

List Posts in a Category

Retrieve the ID of the ‘Technology’ category and list its posts:

$cat_id = get_cat_ID('Technology');
$tech_query = new WP_Query('cat=' . $cat_id);
if ($tech_query->have_posts()) {
    while ($tech_query->have_posts()) {
        $tech_query->the_post();
        echo '<h2>' . get_the_title() . '</h2>';
    }
}

Retrieve the ID of the ‘Food’ category and display its link:

$cat_id = get_cat_ID('Food');
$cat_link = get_category_link($cat_id);
echo '<a href="' . esc_url($cat_link) . '">Visit our Food category</a>';

Retrieve the ID of the ‘Lifestyle’ category and set a featured image:

$cat_id = get_cat_ID('Lifestyle');
update_option('lifestyle_featured_image', 'your-image-url-here');

Get Category Posts Count

Retrieve the ID of the ‘Health’ category and display its posts count:

$cat_id = get_cat_ID('Health');
$health_cat = get_category($cat_id);
echo 'The Health category has ' . $health_cat->count . ' posts.';