Skip to content

Instantly share code, notes, and snippets.

@lepittenger
Created July 31, 2017 02:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lepittenger/96ea9ce2d78a27d66eab352a912c4c75 to your computer and use it in GitHub Desktop.
Save lepittenger/96ea9ce2d78a27d66eab352a912c4c75 to your computer and use it in GitHub Desktop.
Loop Through CPTs + Group by Custom Taxonomy Terms
<?php
/**
*
* Loop through some custom post types and group them by taxonomy term,
* outputting the taxonomy term names before the set of posts
*
*/
// get all of the custom taxonomy terms
$taxonomy = 'my_custom_taxonomy';
$args = array(
'orderby' => 'id',
'order' => 'ASC',
);
$taxonomy_terms = get_terms($taxonomy, $args);
// if there are some taxonomy terms, loop through each one and get the posts in that term
if($taxonomy_terms) {
foreach($taxonomy_terms as $taxonomy_term) {
$args = array(
'post_type' => 'my_cpt',
"$taxonomy" => $taxonomy_term->slug,
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : ?>
// output the taxonomy name for the current term
<h2><?php echo $taxonomy_term->name; ?></h2>
<div class="cpts-wrap">
// loop over the posts
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile; ?>
</div><!-- .cpts-wrap -->
<?php wp_reset_postdata(); // so nothin' weird happens to other loops
endif;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment