2

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.

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

  • 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 Nov 10 '18 at 23:57
9

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

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 .' ';   
         }                                      
    }?>
  • Doesn't answer the question. Asker wanted the ID of the category, not a list of names printed out. – Jacob Peattie Jul 8 '18 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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