Get a category name/slug/id for a post or archive page

There's obviously a little context missing for this paste, but the basic idea should be clear ;-)

Raw
<?php

if ( is_single() ) {
    $cats =  get_the_category();
    $cat = $cats[0]; // let's just assume the post has one category
}
else { // category archives
    $cat = get_category( get_query_var( 'cat' ) );
}
$cat_id = $cat->cat_ID;
$cat_name = $cat->name;
$cat_slug = $cat->slug;
?>

3 comments

  1. avatar
    wrote this comment on

    Thanks for this. I was having a heck of a time trying to get the category ID from within a category archive page.

  2. avatar
    wrote this comment on
    Thanks for this... got me out of 3 hours of blockade :D
  3. avatar
    wrote this comment on
    :-)

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo