2

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?

4

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

You can simply use

$categories = get_the_category();

to get the assigned categories.

1

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.