TransWikia.com

How to get category id of current post?

WordPress Development Asked by jrcollins on January 24, 2021

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

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

Correct answer by swibo on January 24, 2021

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

Answered by cameronjonesweb on January 24, 2021

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;
}

Answered by Jan Desta on January 24, 2021

global $post;
$postcat = get_the_category( $post->ID );
    if ( ! empty( $postcat ) ) {
       foreach ($postcat  as $nameCategory) {
           echo $nameCategory->name .' ';   
         }                                      
    }?>

Answered by Nguyễn Tiến Dũng on January 24, 2021

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!

Answered by Govind Kumar on January 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP