Getting the Category ID in a Category Template

Many templates in the WP Codex are somewhat poorly documented, especially the Author Template and the Category Template to name a few.

On building the Bangumi.WP WordPress theme, I came across the certain challenge of getting the category’s ID in the category template page. (In my case I needed to loop through the Tags of all posts in the category to provide a category specific ‘Tag Cloud’) Not an easy task on first sight.

WordPress uses this awkward ‘The Loop’ sequence to display posts. Instead of returning post data in an array, it uses ‘the_post’ to fetch another post for display. Also, WordPress apparrently doesn’t consider ‘Category’ and ‘Author’ pages anyting different from ‘Archive’ pages, so there doesn’t seem to be a method to acquire data on the subject (also in the case of author pages on ‘Author_ID’)

After extensive searching, I was able to come up with this. Hope it’s helpful for some of you who need to get the category ID in a category template.

global $current_category;
$cat_array = get_the_category();
if(is_array($cat_array) && count($cat_array) > 1) {
    $current_category = $cat_array[0];//First record
    $current_id = $current_category->cat_ID;
    //No posts at all in the category
    $current_category = false;
    $current_id = -1;//Non existant

Now this is not a very reliable method, but it usually gets the job done. Main problem is when there are no posts under a category.