The Support Forums will be in read-only mode for a scheduled maintenance window on 01 September 2016 14:00 UTC - 20:00 UTC. More information.

get_the_category() while browsing in a subcategory? (4 posts)

  1. ixwa
    Posted 5 years ago #

    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?

  2. Michael
    Forum Moderator
    Posted 5 years ago #

    get_the_category() is meat to retrieve categories of a post; used without the post-id, it does not give reliable results.

    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; ?>

  3. ixwa
    Posted 5 years ago #

    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.

  4. ixwa
    Posted 5 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic