Get all children categories using get_terms()
. Loop through each term and run a new query using tax_query
.
Example:
<?php if ( get_queried_object()->parent == 0 ) : // parent cat ?>
<h2>Showing all children</h2>
<?php
$args = array(
'hide_empty' => false,
'parent' => get_queried_object()->term_id
);
$terms = get_terms( 'category', $args );
if ( $terms ) echo '<ul>';
foreach( $terms as $term ) {
$the_post = new WP_Query(array(
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $term->term_id
)
)
));
?>
<?php while ( $the_post->have_posts() ) : $the_post->the_post(); ?>
<li><a href="https://wordpress.stackexchange.com/questions/71607/<?php echo get_term_link( $term,"category'); ?>"><?php echo $term->name; ?></a> (Last article: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>)</li>
<?php endwhile; wp_reset_query(); ?>
<?php
} //endforeach
if ( $terms ) echo '</ul>';
?>
<?php else: // child ?>
<?php
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
?>
<?php endif; ?>