Question

I am trying to query for post titles grouped by their parent term:

Term Name 1
Post Title 1
Post Title 2

Term Name 2
Post Title 1
Post Title 2

e.t.c.

I have created a custom post and taxonomy. So far the code I have runs through each Term Name, but I am unable to get the Post Titles grouped under their parent terms :( I am also not sure if I should use new wp_query in this situation?

            <?php 
            $term_args = array(
                'parent' => 0,
                'orderby' => 'name',
                'order' => 'ASC',
                'hierarchical' => false,
                'hide_empty' => false
            );
            $terms = get_terms('musicians', $term_args);        

            $music_args = array(
                'post_type' => 'tf_musicians',
                'orderby' => 'title',
                'order' => 'ASC',
                'hierarchical' => false,
                'posts_per_page' => -1,             
            );
            $musicians = get_posts($music_args);    
                foreach( $terms as $term){
            echo '<div class="inner-content">';
                echo '<a name="back-point"></a>';                       
                echo '<h2 class="line-spc-sml">'.$term->name.'</h2>';                       
                echo '<ul class="inner">';  

                foreach ($musicians as $musician){  
                    if(has_term('2013','musicians',$musician->ID)) {
                        echo '<li>';                
                            echo '<a class="strong"  href=', get_permalink($musician->ID), '>', $musician->post_title, '</a>';      
                        echo '</li>';                                   
                    }
                    }

                echo '</ul>';
            echo '</div>';  
        }

Thanks in advance

Was it helpful?

Solution

You need to get posts in the loop of terms

foreach ($terms as $term) {

 $music_args = array(
 'post_type' => 'tf_musicians',
 'orderby' => 'title',
 'order' => 'ASC',
 'hierarchical' => false,
 'posts_per_page' => -1,
 'your taxonony goes here' => $term->name
  );

 $musicians = get_posts($music_args);
 echo '<div class="inner-content">';
 echo '<a name="back-point"></a>';
 echo '<h2 class="line-spc-sml">' . $term->name . '</h2>';
 echo '<ul class="inner">';

 foreach ($musicians as $musician) {

 echo '<li>';
 echo '<a class="strong"  href=', get_permalink($musician->ID), '>', $musician->post_title, '</a>';
 echo '</li>';

 }

 echo '</ul>';
 echo '</div>';
 }

Note provide the taxonomy name in 'your taxonony goes here' => $term->name

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top