WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. skywalker84
    Member
    Posted 1 year 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;

    and

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

    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. alchymyth
    Forum Moderator
    Posted 1 year ago #

    http://codex.wordpress.org/Function_Reference/get_the_category
    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
    Member
    Posted 1 year 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