Here is the code…It may help you to display layout as you wanted.
Also Here I have used post type as product and taxonomy as product_cat
so you must need to change that as your code. The layout looks like this http://prntscr.com/mjxvzm
<?php
$post_type="product";
$taxonomy = 'product_cat';
$terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => true,
'parent' => 0,
));
if(! empty($terms) && !is_wp_error($terms)): ?>
<ul>
<?php foreach($terms as $term){ $parent_term_id = $term->term_id; $parent_term_slug = $term->slug; ?>
<li><a href="https://wordpress.stackexchange.com/questions/328438/<?php echo get_term_link($term->slug,$taxonomy); ?>"><h2><?php echo $term->name; ?></h2></a></li>
<?php
$args = array(
'parent' => $parent_term_id,
'hide_empty' => true,
);
$sub_cat_terms = get_terms($taxonomy, $args);
if(! empty($sub_cat_terms) && !is_wp_error($sub_cat_terms)): ?>
<ul>
<?php foreach($sub_cat_terms as $sub_cat_term){ $sub_cat_term_link = get_term_link( $sub_cat_term ); $child_term_slug = $sub_cat_term->slug; ?>
<li><a href="<?php echo $sub_cat_term_link; ?>"><h3><?php echo $sub_cat_term->name; ?></h3></a></li>
<?php
$args = array(
'post_type' => $post_type,
'post_status' => array('publish'),
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $child_term_slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) { ?>
<ul>
<?php while($loop->have_posts()) : $loop->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4></a></li>
<?php endwhile; ?>
</ul>
<?php } ?>
<?php } ?>
</ul>
<?php else: ?>
<?php $args = array(
'post_type' => $post_type,
'post_status' => array('publish'),
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $parent_term_slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) { ?>
<ul>
<?php while($loop->have_posts()) : $loop->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4></a></li>
<?php endwhile; ?>
</ul>
<?php } ?>
<?php endif;?>
<?php } ?>
</ul>
<?php endif;?>