Get current category ID of the active page

2019-01-16 05:50发布

Looking to pull the category ID of a specific page in WordPress that is listing all posts using that specific category. Tried the below but not working. I am able to get the category name using single_term_title.

$category = single_term_title("", false);
$catid = get_cat_ID( $category );

$category is displaying "Entertainment" for example. But I also need the ID of "Entertainment". How would I go about this?

9条回答
姐就是有狂的资本
2楼-- · 2019-01-16 06:16

I think some of the above may work but using the get_the_category function seems tricky and may give unexpected results.

I think the most direct and simple way to access the cat ID in a category page is:

$wp_query->query_vars['cat']

Cheers

查看更多
爷的心禁止访问
3楼-- · 2019-01-16 06:18

You can try using get_the_category():

$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
查看更多
何必那么认真
4楼-- · 2019-01-16 06:19

The oldest but fastest way you can use is:

$cat_id = get_query_var('cat');
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-16 06:20

If it is a category page,you can get id of current category by:

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

If you want to get category id of any particular category on any page, try using :

$category_id = get_cat_ID('Category Name');
查看更多
Root(大扎)
6楼-- · 2019-01-16 06:20

I found this question whilst looking for exactly what you asked. Unfortunately you have accepted an incorrect answer. For the sake of other people who are trying to achieve what we were trying to achieve, I thought I'd post the correct answer.

$cur_cat = get_cat_ID( single_cat_title("",false) );

As you said single_term_title("", false); was correctly returning the category title, I'm not sure why you would have had troubles with your code; but the above code works flawlessly for me.

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-16 06:30

I used this for breadcrums in the category template page:

$cat_obj = $wp_query->get_queried_object();
$thiscat_id = $cat_obj->term_id;
$thiscat = get_category($thiscat_id);
$parentcat = get_category($thiscat->parent);
查看更多
登录 后发表回答