Created
January 21, 2015 17:03
-
-
Save wpmark/afc43c986fb37966a099 to your computer and use it in GitHub Desktop.
Query Posts from Different Terms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* get the terms for the taxonomy */ | |
$terms = get_terms( | |
'taxonomy_name_here', | |
array( | |
'hide_empty' => false | |
) | |
); | |
/* check we have terms to output */ | |
if( ! empty( $terms ) ) { | |
/* loop through the terms */ | |
foreach( $terms as $term ) { | |
/* output the term title */ | |
echo '<h2>' . esc_html( $term->name ) . '</h2>'; | |
/* build a query to query posts from this term */ | |
$term_posts = new WP_Query( | |
array( | |
'post_type' => 'cpt_name_here', | |
'posts_per_page' => -1, | |
'tax_query' => array( | |
array( | |
'taxonomy' => 'taxonomy_name_here', | |
'field' => 'id', | |
'terms' => $term->term_id, | |
), | |
), | |
) | |
); | |
/* check we have posts to show */ | |
if( $term_posts->have_posts() ) { | |
/* loop through posts */ | |
while( $term_posts->have_posts() ) : $term_posts->the_post(); | |
/* each posts output here */ | |
?> | |
<article <?php post_class(); ?>> | |
<h3><?php the_title(); ?></h3> | |
<?php the_excerpt(); ?> | |
</article> | |
<?php | |
/* end loop */ | |
endwhile; | |
} // end if have posts | |
/* reset the query */ | |
wp_reset_query(); | |
} | |
} // if have terms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment