Display posts by taxonomy and taxonomy child

Question

I am trying to show my CPT posts grouped by child taxonomies (in archive-CPT.php) in something that looks like this…

Parent taxonomy 1
Child Taxonomy 1
* Post 1
* Post 2

Child Taxonomy 2
* Post 3
* Post 4

Parent taxonomy 2
Child Taxonomy 1
* Post 5
* Post 6

Child Taxonomy 2
* Post 7
* Post 8

What I have so far is:
Parent taxonomy 1
Post 1
Post 2
Post 3
Post 4

Parent taxonomy 2
Post 5
Post 6
Post 7
Post 8

My code is as follow:

        <?php if ( have_posts() ) : ?>
<?php  
$custom_terms = get_terms('product_category');
foreach($custom_terms as $custom_term) {
wp_reset_query();
    $args = array(
        'post_type' => 'product',
        'child_of' => $custom_terms ,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_category',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
 );

 $loop = new WP_Query($args);
 if($loop->have_posts()) {
    echo '<h2>'.$custom_term->name.'</h2>';

    while($loop->have_posts()) : $loop->the_post();
        echo '<a href="'.get_permalink().'">'.get_the_title().'</a><br>';
    endwhile;
 }}?>

Any help would be really apreciated!

Thanks!

0
, , sandra nanou 3 years 2020-04-07T08:51:54-05:00 0 Answers 95 views 0

Leave an answer

Browse
Browse