1

The following code works to display all child categories of a parent (when viewing a parent category), and all siblings of a child category (when viewing a child category) within sidebar.php. The same sidebar is pulled into both posts and pages.

I'd like to take it a step further so it also works when viewing a post, instead of only categories and child categories. On a post, I'd like all child categories of the category assigned to a post to display. After spending countless hours, I'm at a loss. Can anyone help me with this?

    <ul>                
            <?php if (is_category( )) {                             
                  $cat = get_query_var('cat');
                  $thiscat = get_category ($cat);
                  $parent = $thiscat->parent;
                  $img = get_option('z_taxonomy_image' . $thiscat->term_id);

                  if ($parent != '') {

                        wp_list_categories( array(
                        'child_of' => $parent,
                        'exclude' => $cat,
                        'title_li' => 0
                    ) );
                    }

                  else {

                        wp_list_categories( array(
                        'child_of' => $cat,
                        'title_li' => 0
                    ) );
                  }

            } 
            ?>

            </ul>

1 Answer 1

1

get the category or categories of the single post with get_the_category() and loop through them, calling the child category lists if available.

<ul>
<?php 
if( is_single() ) {
    $post_cats = get_the_category();
        foreach( $post_cats as $post_cat ) {
            wp_list_categories( array(
                'child_of' => $post_cat->term_id,
                'title_li' => 0,
                'show_option_none' => ''
            ) );
    }
}
?>
</ul>
3
  • See this link for an example sidebar like mine. The below lists the subcategory assigned my post instead of all subs under same parent: <?php if( is_single() ) { $cats = array(); foreach (get_the_category($post_id) as $c) { $cat = get_category($c); array_push($cats, $cat->name); } if (sizeOf($cats) > 0) { $post_categories = implode(', ', $cats); } else { $post_categories = 'Not Assigned'; } echo $post_categories; } ?>
    – jlohse22
    Commented Jan 20, 2017 at 21:13
  • I apologize the formatting wouldn't take in my comment above. Do you have any suggestions on how I could list not just the sub-category assigned to my post, but all other siblings as well? The code you sent didn't display any categories assigned to my post.
    – jlohse22
    Commented Jan 20, 2017 at 21:15
  • This helped with something else. Thanks Michael. Commented May 29, 2022 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.