4

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.

5 Answers 5

0
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); ?>

1
  • 2
    Welcome to the site, @swibo. This answer could use a little more clarity. Perhaps explain what you're doing and why, as well as why this answers the original question.
    – butlerblog
    Commented Nov 10, 2018 at 23:57
16

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!

0
5

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];
1

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;
}
-1
global $post;
$postcat = get_the_category( $post->ID );
    if ( ! empty( $postcat ) ) {
       foreach ($postcat  as $nameCategory) {
           echo $nameCategory->name .' ';   
         }                                      
    }?>
1
  • 1
    Doesn't answer the question. Asker wanted the ID of the category, not a list of names printed out. Commented Jul 8, 2018 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.