2

I found this post, but it was never answered. I'm looking for the same thing, haven't been able to find a solution so far.

My problem is that I can't find a way to list subcategories unique to each post on a category archive page. My markup is currently this:

<article <?php post_class( 'grid_item' ); ?>>
  <div class="grid_item--inner">
    <?php the_post_thumbnail(); ?>
    <header>
      <a class="cat_card--link" href="<?php the_permalink(); ?>">
        <h2 class="cat_card--title"><?php the_title(); ?></h2>
        <?php get_template_part('templates/entry-meta'); ?>
      </a>
    </header>
    <div class="cat_card--cats">
      <?php wp_list_categories('title_li=&style=none'); ?>
    </div>
  </div>
</article>

This of course will list all subcategories of the current page's category. Looking through the WP codex documentation, I haven't been able to find a way to list only the applicable subcategories of each post. Is this possible? If so, how do I achieve this?

EDIT: To clarify, I'm interested in listing each subcategory like so:

Parent Category: "Video"
  - Post 1: Subcategory "Comedy"
  - Post 2: Subcategory "Action"
  - Post 3: Subcategories "Comedy, Action"

Where each post only lists the subcategories it uses.

1

1 Answer 1

3

If you want to list only child categories of the current category, set the child_of argument to the current category ID.

wp_list_categories(
    array(
        'child_of' => get_queried_object_id(), // this will be ID of current category in a category archive
        'style' => 'none',
        'title_li' => ''
    )
);

EDIT- To list only child categories per-post of the current category, you'll need to filter the list of each post's terms to check that parent is the current category ID.

$terms = get_the_terms( get_the_ID(), 'category' );

if( $terms && ! is_wp_error( $terms ) ){
    echo '<ul>';
    foreach( $terms as $term ) {
        if( get_queried_object_id() == $term->parent ){
            echo '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
        }
    }
    echo '</ul>';
}
3
  • Thanks for the reply! This is a huge step in the right direction, but it's listing all subcategories being used for each post. I've edited my OP to clarify what I'm trying to achieve.
    – 88 MPG
    Commented Oct 15, 2015 at 20:14
  • @88MPG - see edit above.
    – Milo
    Commented Oct 15, 2015 at 20:43
  • Works like a charm and is definitely not something I would've been able to discover on my own. Thanks again, I really appreciate it.
    – 88 MPG
    Commented Oct 15, 2015 at 20:55

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.