Created
July 31, 2017 02:14
-
-
Save lepittenger/96ea9ce2d78a27d66eab352a912c4c75 to your computer and use it in GitHub Desktop.
Loop Through CPTs + Group by Custom Taxonomy Terms
This file contains hidden or 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 | |
/** | |
* | |
* 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