Taxonomy archive template to have conditional logic for displaying child categories

I have a custom post-type “downloads”, and within the downloads menu, I have download categories, the taxonomy name is “downloadcats”.

My Downloads page uses a page template that lists all categories in the “downloadcats” taxonomy, this only shows parent categories. When a category is clicked, it uses the taxonomy archive template (taxonomy-downloadcats.php) and what I am trying to do is use conditional to say if there are child categories, display a list, otherwise show a list of posts.

In my taxonomy-downloadcats.php at the moment I have the following:

<?php 
$term = get_queried_object();

$children = get_terms( $term->taxonomy, array(
'parent'    => $term->term_id,
'hide_empty' => false
) );
// print_r($children); // uncomment to examine for debugging
if($children) { // get_terms will return false if tax does not exist or term wasn't found.

echo 'show child categories';
} else {
    if (have_posts()) :
    while (have_posts()) : the_post(); ?>
    <li><?php the_post_thumbnail('post-image'); ?>
    <a href="https://wordpress.stackexchange.com/questions/169046/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
    <?php endif; ?>
<?php } ?>

The conditional statement is correct as if the category has no children it does show posts and if there are child categories, it displays “show child categories”, I need to know what goes in there to make the parent’s children appear.

Thanks

3 Answers
3

You are so very close here, you can almost smell it. Here is how you would complete your code:

You already have all your child terms stored in an array called $children. To display these, you simply need a foreach loop. Something like this will do the trick. (You can just extend on this, simply do a var_dump or print_r to get the available objects you can use)

foreach ( $children as $child ) {
    echo $child->name; //very basic, display term name
}

If you need to get a link to the term, make use get_term_link

Leave a Comment