Skip to content

Instantly share code, notes, and snippets.

@wpmark
Created January 21, 2015 17:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmark/afc43c986fb37966a099 to your computer and use it in GitHub Desktop.
Save wpmark/afc43c986fb37966a099 to your computer and use it in GitHub Desktop.
Query Posts from Different Terms
<?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