Custom taxonomy template shows different content if there are children

Question

I am trying to create a template for my custom post type (products) custom taxonomy (product_category) that will show sub categories if there are any and but if there aren’t, then it should list the products.

As an example

categories:

category1
category2
-sub-category1
-sub-catetory2
category3

so if the url is loaded (/product_category/category1) then it will list the products in that category.

However if (/product_category/category2) is loaded, then it will show the names “subcategory1” and “subcategory2” but no actual products.

Here is what I came up with so far, but it feels “hacky” is there a better way to do this?

<?php
get_header(); ?>

    <div id="primary">
        <main id="main">
            <?php

            do_action( 'generate_before_main_content' );

            if ( have_posts() ) :

                $term = get_queried_object();
                $term_id = $term->term_id;
                $taxonomy_name = $term->taxonomy;

                $termchildren = get_term_children( $term_id, $taxonomy_name );
                if ( $termchildren  ) {
                        //there are kids...just show the children categories.
                        echo $termchildren;
                } else { 
                    //no kids...right on to the products.
                    echo '<div class="productCategories grid">';
                        while ( have_posts() ) : the_post();
                            ?>
                            <div class="product_cat">
                                <a href="<?php the_permalink();?>">
                                    <?php the_post_thumbnail('small');?>
                                    <h2><?php the_title();?></h2>
                                </a>
                            </div>
                            <?php
                        endwhile;
                    echo '</div>';
                }
            else :
                get_template_part( 'no-results', 'archive' );
            endif;
            ?>
        </main><!-- #main -->
    </div><!-- #primary -->

    <?php
get_footer();
0
rudtek 4 months 0 Answers 15 views 0

Leave an answer