Get custom category name or id on archive.php page WordPress

How can I “fetch” custom category name or id on archive.php page. So when i’m on that page template, how can i know which custom category posts are showing?

Related posts

Leave a Reply

5 comments

  1. Use get_queried_object(); to retrieve the currently-queried object.

    In a taxonomy term case:

    //Custom taxonomy is project_type, custom term is web-design
    $obj = get_queried_object();
    
    echo '<pre>';
    print_r( $obj );
    echo '</pre>';
    

    Displays the following:

    stdClass Object
    (
        [term_id] => 56
        [name] => Web Design
        [slug] => web-design
        [term_group] => 0
        [term_taxonomy_id] => 56
        [taxonomy] => project_type
        [description] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        [parent] => 0
        [count] => 0
    )
    

    Hope it helps!

  2. Check if this code helps ??

    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. If you are trying to display the current category on your archive.php page, for instance, if your url is:

    www.sitename.com/category/design
    

    Then to echo ‘design’ you would use the following:

    single_cat_title();
    

    On my archive page I have the following:

    <h1 class="page-heading"><?php single_cat_title(); ?></h1>
    

    That displays the category ‘design’ in an h1 tag. I hope this helps someone.

  4. The simple is the best

    $term_id       =    get_queried_object_id();
    $prod_term        =    get_term($term_id,'product_cat');
    $current_cat_slug =    $prod_term->slug;