What you are doing
Your foreach
is nested inside while (have_posts()) : the_post();
. This while loop, loops through each of your posts (in the genre ‘hip_hop’).
So for each post in the genre ‘hip_hop’, you find the post’s taxonomy terms for the taxonomy ‘sub_genre’ (this is the contents of $cam_brands
). Then, for each associated term (in $cam_brands
) you get all posts associated to that term (or
$brand
).
You final foreach
loops through each of these posts and displays them.
What I think you are trying to do
I’m not aware of any native and straightforward way WordPress can ‘split’ all the posts of a particular taxonomy term into it’s children. But the following will do that (albeit, not in a particularly efficient way).
Also, it appears ‘sub_genre’ is a separate taxonomy from ‘genre’ – am I right? If you want a parent-child relationship, you should simply make ‘genre’ a hierarchal taxonomy, and create sub-genres in the same way that you create ‘sub-categories’. Once you’ve done that, the following should work with the below caveats.
$term = get_queried_object();
//Get all children of this term;
$children = get_terms( 'genre',
array(
'parent'=>$term->term_id;
) ) ;
if($children):
//We have an array of child (of current genre) terms. Loop through and display the posts
foreach($children as $child):
echo '<h2>'.$child->slug.'</h2>';
// The Query - get all posts for this child-genre.
$args = array('post_type' => 'track', 'taxonomy' => 'genre', 'term' => $child->slug, 'post_status' => 'publish','posts_per_page' => -1);
$child_posts = new WP_Query ($args);
// The Loop - display all posts for this child-genre.
while ( $child_posts->have_posts() ) : $child_posts->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
endforeach;
else:
//On genre with no children - you may want to do something else.
echo 'No sub-genre for this genre found';
endif;
Caveats
- This code isn’t tested 😀 (but should work)
- It relies on your genre/sub-genres all being part of one hierarchal
- Visiting a genre with no children will display the ‘no sub-genre’ message.
- Tracks which have are associated with a genre term, but not any of its children will not be displayed.