Using WordPress ‘get_catname()’ PHP function

The get_catname() WordPress PHP function retrieves the category name by the category ID.

Usage

get_catname($cat_id);

Example:

$cat_id = 5;
$category_name = get_catname($cat_id);
echo $category_name; // Output: "Travel"

Parameters

  • $cat_id (int) – Required: The category ID.

More information

See WordPress Developer Resources: get_catname()

Examples

Display category name in a post loop

Retrieve the category name and display it in a post loop.

if (have_posts()) {
    while (have_posts()) {
        the_post();
        $category = get_the_category();
        $cat_id = $category[0]->cat_ID;
        $category_name = get_catname($cat_id);
        echo "Category: " . $category_name;
    }
}

Display list of categories with their names

Retrieve a list of categories and display their names.

$categories = get_categories();
foreach ($categories as $category) {
    $cat_id = $category->cat_ID;
    $category_name = get_catname($cat_id);
    echo "Category: " . $category_name . "<br>";
}

Get category name from a post ID

Retrieve the category name for a specific post ID.

$post_id = 100;
$category = get_the_category($post_id);
$cat_id = $category[0]->cat_ID;
$category_name = get_catname($cat_id);
echo "Category: " . $category_name;

Retrieve the category name and display it with a link to its archive page.

$cat_id = 5;
$category_name = get_catname($cat_id);
$category_link = get_category_link($cat_id);
echo '<a href="' . $category_link . '">' . $category_name . '</a>';

Create a dropdown of category names

Create a dropdown of category names using the get_catname() function.

$categories = get_categories();
echo '<select>';
foreach ($categories as $category) {
    $cat_id = $category->cat_ID;
    $category_name = get_catname($cat_id);
    echo '<option value="' . $cat_id . '">' . $category_name . '</option>';
}
echo '</select>';