WordPress.org

Support

Support » How-To and Troubleshooting » get_the_category() while browsing in a subcategory?

get_the_category() while browsing in a subcategory?

  • I’m a bit perplexed by this WP behavior: When I browse the posts for a category that has a parent category, WP seems unable to get any data for the parent category.

    For example:

    if (is_category('3')) { //Main category 3
    
    	if (is_category('18')) { //A subcategory of category 3
    	echo $cat->cat_name;
    	}
    
    }

    Even though I’m still in the main category 3 “environment” all data in get_the_category() is now only displaying subcategory (18) data.

    Is there a WP PHP call or a method to ensure that info for the parent category is still maintained on the page, even if I’ve clicked on a subcat index/post/page?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Michael
    Forum Moderator

    @alchymyth

    get_the_category() is meat to retrieve categories of a post; used without the post-id, it does not give reliable results.
    http://codex.wordpress.org/Function_Reference/get_the_category

    can you post a complete code?

    your snippet is possibly not working:
    see the use of is_category() http://codex.wordpress.org/Function_Reference/is_category

    WP seems unable to get any data for the parent category

    to show the id of the parent category, try to use:
    <?php echo get_category(get_query_var('cat'))->category_parent; ?>

    Hmmmmmm. This is surprisingly difficult for what is really just a need to maintain a visual category->subcategory relationship.

    Your code
    <?php echo get_category(get_query_var('cat'))->category_parent; ?>
    was very helpful for solving the first part of the problem.

    I guess my question is: Once I’m already looking at a subcategory post, and I use the above code to get the cat’s parent cat ID, how do I use this to get at the parent category’s own data vars?

    Something like:

    $parentCat = get_category_VARS('3'); //This call doesn't exist
    $parentCatName = $parentCat->category-name;

    Anything like this?

    I’m sure I’m missing a WP call somewhere here but all I can find is get_the_category or get_category.

    Well after much time wrestling with this I’ve come to the conclusion that it’s far more trouble than it’s worth. When a header menu references not just pages, but categories and posts also, it’s very difficult to present any kind of visual continuity.

    Seems like instead of using categories, the best way to build a truly custom, multi-level menu is to use pages and child pages.

    Not an ideal solution, but easier to implement.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘get_the_category() while browsing in a subcategory?’ is closed to new replies.