Using WordPress ‘get_the_category_by_ID()’ PHP function

The get_the_category_by_ID() WordPress PHP function retrieves the category name based on the given category ID.

Usage

To use the function, simply provide the category ID as the input:

echo get_the_category_by_ID( $category_id );

Parameters

  • $cat_id (int) – Required. The category ID for which the name is to be retrieved.

More information

See WordPress Developer Resources: get_the_category_by_ID

Examples

Display the Category Name by ID

This example displays the category name for the given category ID.

$category_id = 3;
$category_name = get_the_category_by_ID($category_id);
echo 'Category Name: ' . $category_name;

Display Post Categories

This example fetches and displays the categories of a post.

// Get post categories
$post_categories = get_the_category();

// Loop through post categories and display their names
foreach ($post_categories as $category) {
    $category_name = get_the_category_by_ID($category->term_id);
    echo 'Category Name: ' . $category_name . '<br>';
}

Add Category Name as CSS Class

This example adds the category name as a CSS class to an HTML element.

$category_id = 5;
$category_name = get_the_category_by_ID($category_id);
echo '<div class="category-' . $category_name . '">Content goes here</div>';

Display Category Name in a List

This example displays a list of category names using their IDs.

$category_ids = array(1, 2, 3, 4, 5);
echo '<ul>';
foreach ($category_ids as $category_id) {
    $category_name = get_the_category_by_ID($category_id);
    echo '<li>' . $category_name . '</li>';
}
echo '</ul>';

Show a Custom Message for a Specific Category

This example shows a custom message only for a specific category by checking its ID.

$post_categories = get_the_category();
$special_category_id = 7;

foreach ($post_categories as $category) {
    if ($category->term_id == $special_category_id) {
        $category_name = get_the_category_by_ID($special_category_id);
        echo 'This post belongs to the ' . $category_name . ' category!';
        break;
    }
}