The get_cat_name() WordPress PHP function retrieves the name of a category from its ID.
Usage
To use the function, simply pass the category ID as an argument:
echo get_cat_name(4);
This will return the name for the category with the ID ‘4’.
Parameters
$cat_id
(int) – Required. The category ID.
More information
See WordPress Developer Resources: get_cat_name()
Examples
Display Category Name
Display the category name with the ID ‘7’:
// Get the category name $category_name = get_cat_name(7); // Display the category name echo $category_name;
Display Category Name in a Sentence
Display the category name in a sentence using the ID ’12’:
// Get the category name $category_name = get_cat_name(12); // Display the category name in a sentence echo "The category name is: " . $category_name;
Display Category Name in an HTML Element
Display the category name within an HTML element, using the ID ‘3’:
// Get the category name $category_name = get_cat_name(3); // Display the category name in an HTML element echo "<h2>" . $category_name . "</h2>";
Check if Category Name Exists
Check if the category with the ID ‘5’ exists before displaying its name:
// Get the category name $category_name = get_cat_name(5); // Check if the category name exists if ($category_name) { echo "The category name is: " . $category_name; } else { echo "The category does not exist."; }
Display Multiple Category Names
Display the names of categories with the IDs ‘1’, ‘2’, and ‘3’:
// Define an array of category IDs $category_ids = array(1, 2, 3); // Loop through the array and display the category names foreach ($category_ids as $cat_id) { echo get_cat_name($cat_id) . "<br>"; }