Is it possible to get the category name of a category given the Post ID, the following code works to get the Category Id, but how can I get the name?
<?php $post_categories = wp_get_post_categories( 4 ); echo $post_categories[0]?>
Thank!
To fetch the post category, you need to use something called as get_the_category() function. $the_cat = get_the_category(); This function returns the current post category if you use it inside a loop. However if you want to use it outside of the loop then you'll need to pass the post ID as a parameter.
Now, if you want to display all your posts from a specific category on a separate page, WordPress already takes care of this for you. To find the category page, you simply need to go to Posts » Categories » View page and click on the 'View' link below a category.
WordPress does provide a function to get the taxonomy information from its slug. The slug is not the same as the name of the taxonomy. Your example only works because they happen to be equal in this particular case. get_taxonomy takes a taxonomy name, not a slug.
You can also view your WordPress category ID by editing it. Simply open a category to edit, and you'll see the category ID in the browser's address bar. It is the same URL that appeared when there was a mouse hover on your category title.
here you go get_the_category( $post->ID );
will return the array of categories of that post you need to loop through the array
$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}
get_the_category
echo '<p>'. get_the_category( $id )[0]->name .'</p>';
is what you maybe looking for.
doesn't
<?php get_the_category( $id ) ?>
do just that, inside the loop?
For outside:
<?php
global $post;
$categories = get_the_category($post->ID);
var_dump($categories);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With