How to get the first category name or id from post

Sponsors

Many people want to know about post category and know more information current category.

Some time we need to use the first category of wordpress post. As we know we can define the multiple category to single article. So if we want retrive the wordpress category then we will get the result in simple php array format. Using that array we can easily extract the first category of post.

In this post I will show how we can achieve that. Using following code we can get the first category ID.

< ?php
$category = get_the_category();
$currentcat = $category[0]->cat_ID;
?>

Using following code we can extract the first category name from the wordpress post.

< ?php
$category = get_the_category();
$currentcat = $category[0]->cat_name;
?>

Above code we can use only in the loop but using the following code we can extract the category
outside the loop also

<?php
global $post;
$categories = get_the_category($post->ID);

$currentcat = $category[0]->cat_ID;
?>
<pre>

same like that.. cat name

 <?php
 global $post;
 $categories = get_the_category($post->ID);

$currentcat = $category[0]->cat_name;
 ?>

<pre>

Incoming search terms:

You may like following Articles!

12 thoughts on “How to get the first category name or id from post

  1. Can I make a suggestion? I think youve got something good here. But what if you added a couple links to a page that backs up what youre saying? Or maybe you could give us something to look at, something that would connect what youre saying to something tangible? Just a suggestion.

  2. Where may I experience monetary value of segments as well as repairs as Audi A3 2007? I’m reasoning of buying an Audi A3 2007 2.0 FSI , usually aspirated. I’d likes To acknowledge where I may experience actual info by what this may price how to repari if A/C broke down, or To substitute shocks, repair a console etc etc. also if everyone thinks this is a capital eating car to grounds of repairs Please let me recognise also. Many thanks

  3. Thanks for the hack. This is exactly what I was looking for. An example and css styling would have made the post much more useful. I need to get the first category of the post on homepage. This will definitely help me out.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>