WordPress: How to get the Category ID on a category page

I was trying to add some custom code and links to my WordPress category pages (the category.php file), but there was no quick and obvious way to get the category ID into the PHP code. After searching around on the web and not finding anything close to what I wanted, I started digging around in the WordPress code and figured out a really short and good solution:

<?php
    $current_cat = get_the_category();
    $current_cat_id = $current_cat ? $current_cat[0]->cat_ID : 0;
?>

Explanation of Code:

  1. The first line in the code ( $current_cat = get_the_category(); ) gets the list of categories of the page you are one. The caveat here is that even though on a category page it will only return one category, it will still be contained in a "list" (i.e., an array). That is why in the second line of code we use only the first element of the array ( $current_cat[0] ).
  2. The second line in the code checks to make sure that the returned category list is valid (this part of the code: " $current_cat ? ") and then uses one of two possible values:
    • $current_cat[0]->cat_ID is used if the returned category list is valid. It is taking the returned list of categories (which will be a list of only one category on a categories page), takes the first element (which is a category “object”), and then takes that category object’s ID.
    • 0 is used if the returned category list is not valid. The ID "0" is considered the global category ID. You could modify this code to do just about anything else you want if a valid category was not returned.

Note that the second line of code uses the shorthand form of an if-then-else statement. The form

expression ? response_if_true : response_if_false;

is interpreted as:

if(expression) { response_if_true } else { response_if_false }

2 thoughts on “WordPress: How to get the Category ID on a category page”

    1. No plugin is needed – that ability is built in to WordPress already. When you are creating a new post (or editing a previous post), all that you need to do is specify a customized “category” for that post instead of using the default “uncategorized” option. When you do that, then the “Categories” menu on the right-side of you blog will be filled with links for all of those customized categories that you have created instead of only listing “Uncategorized”. Those links will go to pages that show a page of posts that are only for that category, like you asked about.

      To specify a category, go edit one of the posts that you have already created, and then on the right-side of the editor screen you will see a list of categories that you can choose and a link to “+ Add New Category” (in case you don’t have an applicable category to select yet).

Leave a Reply

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