Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I need to get category id in single.php. I tried this:
$cat_ID = get_query_var('cat');

It didn't work. What should I use instead?

share|improve this question

2 Answers 2

Use wp_get_post_categories()

Retrieve the list of categories for a post.

<?php wp_get_post_categories( $post_id, $args ) ?>

Be aware that the function returns an array (of category ids) even if you only have one category in your post.

The example below shows how categories are retrieved, and then additional information is retrieved for each category.

$post_categories = wp_get_post_categories( $post_id );
$cats = array();

foreach($post_categories as $c){
    $cat = get_category( $c );
    $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
}

Reference: http://codex.wordpress.org/Function_Reference/wp_get_post_categories

Another Option:

Use get_the_terms();

<?php
    $id = get_the_id();
    $terms = get_the_terms( $id, 'category' );
    // print_r( $terms );
    foreach($terms as $term) {
        echo $term->cat_ID;   
    }
?>
share|improve this answer

You can simply use

$categories = get_the_category();

to get the assigned categories.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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