David Davis
David Davis

Reputation: 13

How to display all subcategories of deepest category on post (WordPress)?

I would like to display (sidebar) all the subcategories (linked) for the second-deepest level category a post belongs to. I have tried various code (like the snippet below that is definitely flawed (it produces duplicates of subcategories in the display list). I think the easiest way might be to follow breadcrumbs (I have a breadcrumbs widget on the same page. So basically just display all subcategories of the deepest level category. (Also, sometimes various categories are checked (in more than one strain of categories eg South Sudan post might be in the strain below, but also checked for the Human Rights category. I don't really care which category strain I display, just so long as it displays one of them).

For example,

On a post about South Sudan news, which is breadcrumbed: World > Africa > East Africa > South Sudan, it would display all the subs of the East Africa category

On a post about Vancouver Island (breadcrumbed World > North America > Canada > BC > Vancouver Island), it would display all sub-categories to BC).

Is there even a way to do this?

The (flawed) code that I've been working with (not sure if there might be a better starting point).

<?php
$post_categories = wp_get_post_categories( $post->ID );
foreach($post_categories as $c){
    $cat = get_category( $c );

    $childCats = get_categories( array('child_of' => $c) );
    if(is_array($childCats)):
        foreach($childCats as $child){ ?>
            <h2><?php echo $child->name; ?></h2>
            <?php
            query_posts('cat='.$child->term_id);
            while(have_posts()):
                the_post();
                $do_not_duplicate = $post->ID;
                //post code stuff here;
            endwhile;
            wp_reset_query();
        }
    endif;
}
?>

Upvotes: 0

Views: 524

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42500

This line will give you the child categories of a given category:

$childCats = get_categories( array('child_of' => $c) );

If I understood you correctly, you need the parent categories, however.

Look into the function get_category_parents(), this might be just what you need:

Returns a list of the parents of a category, including the category, in hierarchical order.

Upvotes: 0

Related Questions