Hello, I have been stumped for a few days on a perfect way to display the posts using my custom post type (track) and the taxonomies ( genre, sub_genre). When a user goes to http://sitename.com/genre/“sub_genre name” , i want all posts of that sub_genre to be categorized by those sub_genre taxonomies with content.
ex..
http://sitename.com/genre/hip_hop
Genre: West
junior test track
Genre: Old School
Song 3 track
Rap title track
Song 2 track
This is the code Im using but but its looping all wrong…
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post();
$cam_brands = get_the_terms( $post->ID, 'sub_genre' );?>
<?php foreach( $cam_brands as $brand ) : ?>
<h3 class="genre-title"> <?php echo $brand->name; ?> </h3>
<?php $wpq = array( 'post_type' => 'track', 'taxonomy' => 'sub_genre', 'term' => $brand->slug, 'post_status' => 'publish','posts_per_page' => -1, 'caller_get_posts'=> 1 );
$brand_posts = new WP_Query ($wpq);?>
<ul>
<?php foreach( $brand_posts->posts as $post ) : ?>
<li> <?php echo $post->post_title; ?> <a class="sc-player" href="<?php echo get('soundcloud_link'); ?>">track</a> </li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
<?php endwhile; ?>
<?php endif; ?>
Its seems to be going through the foreach as many times as there are actual posts in the genre taxonomy rather than the sub_genre.
ex.
Genre:West
junior test track
Genre:Old School
Song 3 track
Rap title track
Song 2 track
Genre:Old School
Song 3 track
Rap title track
Song 2 track
Genre:Old School
Song 3 track
Rap title track
Song 2 track
Any help Please Please Please would be appreciated. My php skills are not the best and the loop is making my brain hurt a little. Thanks
What you are doing
Your
foreach
is nested insidewhile (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.
Caveats