## wp query – Strange behaviour of hierarchical taxonomy archive

Question

Background: I have a hierarchical taxonomy and I’m trying to create a taxonomy template file that lists each of the child terms with the associated posts below each.

So far I have managed to achieve most of this, but I have come across a rather strange situation which I am hoping someone might have an answer for.

What I doing is taking the queried term and getting the child terms for that parent. It then loops through the terms and outputs the posts just with that term. What is strange is that it will get the posts when the term is a top-level term, but if the term should be a child then it doesn’t get the posts, although it does get any child terms of that term.

To illustrate, my taxonomy might be:

Term 1 - 2 posts
Term 2 - 0 posts
- Child A - 2 posts
Term 3 - 2 posts
- Child A - 1 post


Landing on Term 1 I get:

<h3>Post 1</h3>
<h3>Post 2</h3>


Landing on Term 2 I get:

<h2>Child A>
<h3>Child A's Post 1</h3>
<h3>Child A's Post 2</h3>


Landing on Term 3 I get:

<h2>Child A>
<h3>Child A's Post 1</h3>


So terms 1 & 2 I get exactly what I expect, but term 3 only shows the child term and its post, but NOT the 2 posts which has term 3 itself applied to them.

What I expect to see should be:

<h3>Post 1</h3>
<h3>Post 2</h3>
<h2>Child A>
<h3>Child A's Post 1</h3>


(I must admit I struggled to put that in writing, I hope you understand what I mean!)

My code is:

$query_var_taxonomy = get_queried_object()->taxonomy;$query_var_term = get_queried_object()->slug;
$queried_term = get_term_by( 'slug',$query_var_term, $query_var_taxonomy );$args = array(
'taxonomy' => $query_var_taxonomy, 'hide_empty' => false, 'child_of' =>$queried_term->term_id,
);
$terms = get_terms($query_var_taxonomy, $args ); // If this is the last ancestor term then the above will return an empty array, // so we must populate the array with just that one term. if ( empty($terms ) ) {
$obj = new stdClass();$obj->slug = $query_var_term;$terms[] = $obj; } // Loop through each term foreach ($terms as $term ) { //New query for each term, excluding term children$args = array(
'post_type' => 'treatment',
'tax_query' => array( array(
'taxonomy' => $query_var_taxonomy, 'field' => 'slug', 'terms' =>$term->slug,
'include_children' => false,
), ),
);
$query = new WP_Query($args );
if ( $query->have_posts() ) { echo "<h2>" . esc_html($term->name ) . "</h2>";
while ( $query->have_posts() ) {$query->the_post();
the_title( '<h3>', '</h3>' );
}
}
}


The really odd thing is that, if the term is top-level (ie, has no parent) then the posts belonging to that term are output correctly, but if the term is a child term, or if the top-level term has other child terms, then it only shows the other child terms but not the posts of that term.