List all Category Names of a Post in WordPress with this simple PHP code I've provided in this tutorial. If you have a post ID, it's easy to get associated Category Names to that post after reading this short WordPress Tutorial.
$postId = 1;
//note: if you code in single.php, do not need to pass the id
$categories = get_the_category($postId);
//iterate categories and print $category->cat_name
foreach($categories as $category){
echo '<a href="' . get_category_link($category) . '">' . $category->cat_name . '</a>';
}
Explaining the above code
In the first line, we specified $postId
as the post with an ID of 1. But you do not need to specify the post id if you are coding inside the single.php file.
the get_the_category()
function will use the global $post object to return categories if you do not pass the post id.
Then in line 3, we retrieved categories using the get_the_category()
function.
get_the_category()
will return an array of category objects containing the cat_name
field, which we are looking for.
We used foreach
loop from line 6 to iterate categories and print the $category->cat_name
wrapped inside <a>
tag.
If you do not need to link the category name to its page, then remove the link tag, like the below example:
$postId = 1;
//note: if you code in single.php, do not need to pass the id
$categories = get_the_category($postId);
//iterate categories and print $category->cat_name
foreach($categories as $category){
echo $category->cat_name . ',';
}
If you need category names inside an array to use inside custom functions or WordPress plugin development, try the below code:
$postId = get_the_ID();
//retrieve categories for this post
$categories = get_the_category($postId);
//create an array of category names
$categoryNames = array_map( function($category){ return $category->cat_name; }, $categories );
In the above example, we’ve used the PHP array_map function to create an array of category names.
If you are interested in more details about categories in WordPress, I recommend reading my tutorial on Query WordPress Categories.
written by Mehdi Nazari about in WordPress
What do you think about "How to Get Category Names by Post ID in WordPress!"?