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:31

Alternative -

 $catID = the_category_ID($echo=false);

EDIT: Above function is deprecated please use get_the_category()

查看更多
闹够了就滚
3楼-- · 2019-01-16 06:32

I use the get_queried_object function to get the current category on a category.php template page.

$current_category = get_queried_object();

Jordan Eldredge is right, get_the_category is not suitable here.

查看更多
迷人小祖宗
4楼-- · 2019-01-16 06:33
$cats = wp_get_post_terms( $post->ID, 'product_cat' );
foreach($cats as $cat){
/*check for category having parent or not except category id=1 which is wordpress default category (Uncategorized)*/
  if($cat->parent != '0' && $cat->term_id != 1){
    echo '<h2 class="link"><a href="'.get_category_link($cat->term_id ).'">'.$cat->name.'</a></h2>';
    break;
  }
}
查看更多
登录 后发表回答