Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Category name from Post ID

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!

like image 636
user1937021 Avatar asked Jun 25 '13 17:06

user1937021


People also ask

How can I get current post category?

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.

How do I get post by category name in WordPress?

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.

How do I find the taxonomy category name in WordPress?

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.

How do I find the category ID in WordPress?

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.


3 Answers

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

like image 58
M Khalid Junaid Avatar answered Sep 22 '22 16:09

M Khalid Junaid


echo '<p>'. get_the_category( $id )[0]->name .'</p>';

is what you maybe looking for.

like image 31
kaimagpie Avatar answered Sep 21 '22 16:09

kaimagpie


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);
?>
like image 43
Kortschot Avatar answered Sep 22 '22 16:09

Kortschot