Query to Find WordPress Category Name or id from Post id

In one of our previous post we have shown you Get All WordPress Category and Loop Out All Post in Each Category. Now from your client requirements or any other reason you might need to show category information in single post. Here is your most wanted query to find WordPress category name or id from post id or post URL by using get_the_category function.

Query to Find WordPress Category Name or id from Post id

[php]<?php
while (have_posts()) : the_post();
$postid = $post->ID;
$category_detail=get_the_category($postid);
foreach($category_detail as $cd){
$cat_id= $cd->term_id;
$cat_name= $cd->cat_name;
}
?>
<h1><strong><?php echo $cat_name;?></strong></h1>
<p><strong><?php echo category_description( $cat_id ); ?> </strong></p>
<div class="blog_view">
<h2><?php the_title(); ?></h2>
<p><?php the_post(); ?></p>
</div>
<?php endwhile; ?> [/php]

First of all we get post id from while loop in line 3 then we get the category in line 4 by using get_the_category function. As this is an array that’s why we have to use foreach loop to find out exact category of current post. That’s what we did exactly from line 5 to line 7.  You can also get post id from page URL if you didn’t use while loop. 

[php]<?php
$posturl= get_permalink();
$postid = url_to_postid( $posturl );
?>[/php]

Like this WordPress query to find category name or id from post id then we love to here from you …please don’t forget to comment below.

Author: mytutorialguru

Share This Post On

Submit a Comment

Your email address will not be published. Required fields are marked *