Wordpress getting current category ID

2020-05-23 03:54发布

问题:

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?

回答1:

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



回答2:

Try the following

$catID = get_query_var( 'cat' );



回答3:

the_category_ID was deprecated in 2003.

Try this:

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


回答4:

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


回答5:

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



回答6:

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.



回答7:

This writes the variable instead of echoing

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


回答8:

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.



标签: wordpress