So I have a CPT of references (like a dictionary kind of format for music).

In it there are two taxonomies: medium_reference and reference_letter.

The reference_letter lists letters A-Z, while medium_reference lists through the type of reference type it is (person, terminology, company).

I was wondering if it was possible to loop through each letter, and then in that loop, loop through the individual terms.

Something like this (not that this works in anyway possible):

$reference_letters = get_the_terms($post->ID,'reference_letter');
$reference_types = get_the_terms($post->ID,'medium_reference');

if($reference_letters) {
    // Loop through letters
    foreach($reference_letters as $reference_letter => $letter) {

        if($reference_types) {
            // Loop through individual terms
            foreach($reference_types as $reference_type => $type) {
                the_title(); // And other attributes


Does that make sense? And is it possible without having to run multiple get_posts() for each letter?

  • 1
    Check this wordpress.stackexchange.com/questions/97923/… – Marvin3 May 12 '13 at 8:16
  • Well, technically speaking, there's nothing wrong with your approach. It's even better (faster) to run multiple small queries, then a single large one. – Dan Ștefancu May 12 '13 at 12:31
  • @TeddMagwell thanks for that, but it only loops the taxonomies not posts too – markb May 12 '13 at 12:39
  • @DanStefancu yeah I was just hoping to minimise the coding more than anything - also curious! – markb May 12 '13 at 12:41

In case anyone runs into trouble like I did, I figured it out!

$taxonomy_1 = get_terms( 'taxonomy_1', $args_1 );
$taxonomy_2 = get_terms( 'taxonomy_2', $args_2 );

    foreach( $taxonomy_1 as $tax_1 ) {

        foreach( $taxonomy_2 as $tax_2 ) {

            $posts = get_posts(
                    'posts_per_page'   => -1,
                    'post_type'        => 'ENTER-YOUR-CPT',
                    'order'            => 'ASC',
                    'orderby'          => 'title',
                    'taxonomy'         => $tax_2->taxonomy,
                    'term'             => $tax_2->slug,

            foreach( $posts as $post ) {
                setup_postdata( $post ); 
                // ENTER YOUR OWN LOOP the_title(), the_permalink(), etc.

In my case, $taxonomy_1 was my letter (reference_letter) and $taxonomy_2 was my type (medium_reference).

Also in this method, it sorts the posts into their taxonomies based on two $tax_2-> lines in the get_posts().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.