Get current category ID of the active page
Asked Answered
P

13

92

Looking to pull the category ID of a specific page in WordPress that is listing all posts using that specific category. Tried the below but not working. I am able to get the category name using single_term_title.

$category = single_term_title("", false);
$catid = get_cat_ID( $category );

$category is displaying "Entertainment" for example. But I also need the ID of "Entertainment". How would I go about this?

Pliers answered 12/1, 2012 at 3:8 Comment(2)
Is it a normal category page or custom page template?Bumgardner
it is a custom taxonomy - trying to use this on a file named taxonomy-event-categories-entertainment.phpPliers
J
79

You can try using get_the_category():

$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
Jeffjeffcoat answered 12/1, 2012 at 3:47 Comment(6)
$category[0]->cat_ID to be accurate.Daryldaryle
This method actually checks the first category of the first post on the page. If there are no posts or if the first post has multiple categories, this will fail or return incorrect info.Abukir
I agree with @JordanEldredge, this will return incorrect info.Kessia
This will return the first category of the first post of the page.Southport
It will also fail if the viewed page is a subcategory. Check for the output of the $categories array.Trilobite
My test site contain no other category and the post doesn't select it so this return nothing.Choirmaster
T
212

If it is a category page,you can get id of current category by:

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

If you want to get category id of any particular category on any page, try using :

$category_id = get_cat_ID('Category Name');
Twinkle answered 12/1, 2012 at 9:47 Comment(7)
Exactly what I was looking for. Better than the above answer if you are creating a generic Category template as you only get the Category the page will display as opposed to the multi-Category array from the above.Spaceman
It worked perfectly for me. I was having problem getting the ID and worked lovely for me. Saved hours :)Offstage
Need to replace the correct answer! The answer marked correct, misled me.Indiana
This answer has some unnecessary code. The first line of code gets the full category data in get_category function by using one parameter - CATEGORY ID (because this is what get_query_var( 'cat' ) returns). The second line of code actually retrieves the id from the data. This means that the get_category function is completely unused here and if someone wants only the id, then just get_query_var( 'cat' ) should be used!Roast
@RamMeharDeswal is it possible to use this method to get the child category ?Philbo
Good code mate, it works with pagination!!! get_the_category() gave a whole array in pagination instead of the current category. someone should changed the correct answer to this one!Ecumenicism
My test site contain uncategorized my post don't select any category and get_query_var( 'cat' ) return empty.Choirmaster
J
79

You can try using get_the_category():

$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
Jeffjeffcoat answered 12/1, 2012 at 3:47 Comment(6)
$category[0]->cat_ID to be accurate.Daryldaryle
This method actually checks the first category of the first post on the page. If there are no posts or if the first post has multiple categories, this will fail or return incorrect info.Abukir
I agree with @JordanEldredge, this will return incorrect info.Kessia
This will return the first category of the first post of the page.Southport
It will also fail if the viewed page is a subcategory. Check for the output of the $categories array.Trilobite
My test site contain no other category and the post doesn't select it so this return nothing.Choirmaster
H
41

The oldest but fastest way you can use is:

$cat_id = get_query_var('cat');
Homozygote answered 18/6, 2013 at 8:5 Comment(5)
this seems perfect. are there drawbacks to this over Ram Mehar Deswal's answer?Maronite
This is actually the working solution, it will display the category of the viewed page.Trilobite
@Maronite look for Bartosz Górski's comment in Ram Mehar Deswal's answer. He is completly right and this answer right here does all you need.Hallucination
@Hallucination thx for pointing me to that you good SO citizen you! :)Maronite
get_query_var( 'cat' ) is falsy for mePolice
S
24

I use the get_queried_object function to get the current category on a category.php template page.

$current_category = get_queried_object();

Jordan Eldredge is right, get_the_category is not suitable here.

Southport answered 10/1, 2014 at 11:0 Comment(3)
Nice, never seen this one before.Snipes
If the result is not the expected one, invoke wp_reset_query(); to restore the default WP_Query instance.Southport
This is actually the most useful Wordpress function I have ever found. It's usable everywhere: pages, articles, categories etc.Provence
C
4

I think some of the above may work but using the get_the_category function seems tricky and may give unexpected results.

I think the most direct and simple way to access the cat ID in a category page is:

$wp_query->query_vars['cat']

Cheers

Collette answered 12/1, 2012 at 3:9 Comment(1)
Perfect! Thanks.Gonzalo
H
2

if you need the category ID, you would get it via get_query_var, that is capable of retrieving all publicly queryble variables.

$category_id = get_query_var('cat');

here is an example to get the category name

$category_name = get_query_var('category_name');

and of course the all mighty get_queried_object

$queried_object = get_queried_object();

that is returning the complete taxonomy term object (when used on a taxonomy-archive page..)

Hallucination answered 12/3, 2020 at 16:30 Comment(0)
O
2

I tested all these answers and this is the only one which works on all archive page types including posts page.

$category_id = get_the_category( get_the_ID());
$cat_id      = get_category($category_id[0]->term_id);
Outstare answered 15/1, 2022 at 13:0 Comment(0)
K
1

I found this question whilst looking for exactly what you asked. Unfortunately you have accepted an incorrect answer. For the sake of other people who are trying to achieve what we were trying to achieve, I thought I'd post the correct answer.

$cur_cat = get_cat_ID( single_cat_title("",false) );

As you said single_term_title("", false); was correctly returning the category title, I'm not sure why you would have had troubles with your code; but the above code works flawlessly for me.

Kessia answered 21/5, 2013 at 14:16 Comment(0)
A
1

Alternative -

 $catID = the_category_ID($echo=false);

EDIT: Above function is deprecated please use get_the_category()

Afterward answered 4/2, 2015 at 12:28 Comment(1)
FYI: This function has been deprecated.Potential
S
1

I used this for breadcrums in the category template page:

$cat_obj = $wp_query->get_queried_object();
$thiscat_id = $cat_obj->term_id;
$thiscat = get_category($thiscat_id);
$parentcat = get_category($thiscat->parent);
Salience answered 9/8, 2016 at 17:2 Comment(0)
J
0
$cats = wp_get_post_terms( $post->ID, 'product_cat' );
foreach($cats as $cat){
/*check for category having parent or not except category id=1 which is wordpress default category (Uncategorized)*/
  if($cat->parent != '0' && $cat->term_id != 1){
    echo '<h2 class="link"><a href="'.get_category_link($cat->term_id ).'">'.$cat->name.'</a></h2>';
    break;
  }
}
Jude answered 10/2, 2017 at 4:43 Comment(0)
D
0

Tried above for solutions to find cat ID of a post, but nothing worked, used the following instead:

$obj = get_queried_object();
$c_id = wp_get_post_categories($obj->ID);
Diastasis answered 22/1, 2019 at 18:11 Comment(0)
W
0

Here's an efficient method to get category meta data, along with HTML if you want to print it out on the front-end:

    <?php
    
    function custom_get_categories() {
      $categories = get_the_category();
      $uncategorised_id = get_cat_ID('Uncategorized');
      $custom_category_link = '';
    
      foreach ($categories as $category) {
        if($category->category_parent == $uncategorised_id || $category->cat_ID == $uncategorised_id) {
          continue;
        }
        
        $custom_category_link = get_category_link($category->cat_ID); ?>
    
        <a href ="<?php echo $custom_category_link ?>"> 
    <?php echo "\n\nCategory ID: " . $category->cat_ID . "\nCategory Name" . $category->name;  ?> </a>
    
        <?php
      }``
    }
    
     ?>
Witchy answered 16/9, 2021 at 9:54 Comment(2)
Hello Hemant Adhikari. Please separate the text from the code in your post.Hedda
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Ginnifer

© 2022 - 2024 — McMap. All rights reserved.