admin管理员组

文章数量:1323348

I need to get the category id of the current post outside the loop. First I get the category based on the post id:

global $wp_query;
$postcat = get_the_category( $wp_query->post->ID );

Now how to get the category id? I tried: $cat_id = $postcat->term_id; but it's not working.

I need to get the category id of the current post outside the loop. First I get the category based on the post id:

global $wp_query;
$postcat = get_the_category( $wp_query->post->ID );

Now how to get the category id? I tried: $cat_id = $postcat->term_id; but it's not working.

Share Improve this question asked Nov 30, 2016 at 4:32 jrcollinsjrcollins 5712 gold badges15 silver badges30 bronze badges
Add a comment  | 

5 Answers 5

Reset to default -1
function catName($cat_id) {
    $cat_id = (int) $cat_id;
    $category = &get_category($cat_id);
    return $category->name;
}
function catLink($cat_id) {
    $category = get_the_category();
    $category_link = get_category_link($cat_id);
    echo $category_link;
}

function catCustom() {
   $cats = get_the_category($post->ID);
    $parent = get_category($cats[1]->category_parent);
    if (is_wp_error($parent)){
        $cat = get_category($cats[0]);
      }
      else{
        $cat = $parent;
      }
    echo '<a href="'.get_category_link($cat).'">'.$cat->name.'</a>';    
}

USE <a href="<?php catLink(1); ?>"> <?php catName(1); ?>

When you use get_the_category() function to get category's data, it return the array of object so you have to access category id by passing array key, like this $postcat[0]->term_id

global $post;
$postcat = get_the_category( $post->ID );

// try print_r($postcat) ;  

if ( ! empty( $postcat ) ) {
    echo esc_html( $postcat[0]->name );   
}

Hope this help!

Old post I know, but wp_get_post_categories is likely what you want.

$cats = wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) );

This will return an array of category IDs like so

array (size=3)
  0 => int 13
  1 => int 15
  2 => int 120

So if you just want one category ID, you can get that from the first key in the array of category IDs.

$category_id = $cats[0];

An improvement to Govind Kumar answer, as the asker askes about category ID, not the category name. The property name of the object for category ID is "cat_ID".

// get cat ID for general view
$postcat = get_the_category( $query->post->ID );
if ( ! empty( $postcat ) ) {
 echo $postcat[0]->cat_ID;
}
global $post;
$postcat = get_the_category( $post->ID );
    if ( ! empty( $postcat ) ) {
       foreach ($postcat  as $nameCategory) {
           echo $nameCategory->name .' ';   
         }                                      
    }?>

本文标签: categoriesHow to get category id of current post