get_the_category() won't change between category requests (3 posts)

  1. skywalker84
    Posted 2 years ago #

    I have searched all over and can't seem to find any help or docs on why get_the_category doesn't change between category requests.

    Basically what I'm trying to do is have a custom sidebar display on certain categories.
    In category.php I have:

    $category = get_the_category();
    $category_slug = $category[0]->slug;


    if ( in_array($category_slug, $pdi_cats) ) {
        <div id="sidebar-container" class="cat-sidebar-<?php echo $category_slug; ?>">
    	if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar( $category_slug . '-sidebar' ) ) {
    } else {

    which loops through my array of custom categories and if the current category is one of them displays that sidebar.

    The problem is that $category_slug won't change when I change categories. It keeps displaying the first category that I pulled up like it's caching it. Am I totally missing something here?

  2. Michael
    Part-Time Forum Moderator
    Posted 2 years ago #

    does not have reliable results outside of the loop.

    in category.php try and use:

    $category_slug = get_category(get_query_var('cat'))->slug;

  3. skywalker84
    Posted 2 years ago #

    Excellent! Works perfect now thanks!

    Is there a simple explanation why it does not return correct results outside the loop? Just like to know for future reference.

    This tag may be used outside The Loop by passing a post id as the parameter.

    But the id param is optional and says it passes in the current post id.

Topic Closed

This topic has been closed to new replies.

About this Topic