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="https://wordpress.stackexchange.com/questions/205647/<?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 Answer
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>';
}