WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

    $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


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.