'Cant display category ID from functions.php

I want to display the current category number on the category page. I have this code on functions.php of my theme:

echo get_the_category( get_the_ID());

but nothing is displayed. I also tried

$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
echo $category_id;

but nothing is displayed either. Neither with this

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

Why is that?



Solution 1:[1]

On the category.php page, that specific category is what is queried. You would a function that gets the queried object, then echoes the information needed from that object.

Place this function in your functions.php file:

function namespace_get_cat_id() {
    $category = get_queried_object();
    echo $category->term_id;
}

Then, on your category.php page inside the loop, you would call the function:

namespace_get_cat_id();

To see available information you can pull from the queried object, use var_dump().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nimantha