ngplayground
ngplayground

Reputation: 21617

Wordpress getting current category ID

I'm trying to get the current ID of the category page I'm viewing.

I had checked the_category_ID

But this echo'd my result when I used

<?php $catID = the_category_ID(); ?>

Is there a way to get it to return the value to the variable so its hidden?

Upvotes: 20

Views: 85080

Answers (8)

PUSTAKAKORAN.COM
PUSTAKAKORAN.COM

Reputation: 477

This code current to get Category ID:

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

It's work for me, today 18 Oct 2016.

Upvotes: 3

Samyappa
Samyappa

Reputation: 531

You will get current category id in variable,

<?php $catID = the_category_ID($echo);?>

This not print directly, whenever give print statment that time only print.

Upvotes: -3

tejashree mahadik
tejashree mahadik

Reputation: 315

$category= get_queried_object();
echo $category->term_id;

Upvotes: 8

Byteshifter
Byteshifter

Reputation: 126

Function the_category_ID is deprecated. You need to use get_the_category() function instead. E.g.:

$category = get_the_category(); 
echo $category[0]->cat_name;

See more at wordpress codex: get_the_category

Upvotes: 3

Tim
Tim

Reputation: 6441

the_category_ID was deprecated in 2003.

Try this:

if (is_category()) {
    $category = get_category(get_query_var('cat'));
    $cat_id = $category->cat_ID;
}

Upvotes: 6

Jared
Jared

Reputation: 12524

Try the following

$catID = get_query_var( 'cat' );

Upvotes: 8

birgire
birgire

Reputation: 11378

The current category ID is in the global $cat variable, when you are in a category page.

You can test it with:

<?php echo "Current Category ID is: " . $cat ;?>

when you are in for example this page http://example.com/category/test

Upvotes: 48

ngplayground
ngplayground

Reputation: 21617

This writes the variable instead of echoing

<?php $catID = the_category_ID($echo=false);?>

Upvotes: 0

Related Questions