Skip to content

Instantly share code, notes, and snippets.

@Irfan-Ansari
Created February 19, 2014 23:11
Show Gist options
  • Save Irfan-Ansari/9103602 to your computer and use it in GitHub Desktop.
Save Irfan-Ansari/9103602 to your computer and use it in GitHub Desktop.
Get posts and group by taxonomy terms
/**
* Get posts and group by taxonomy terms.
* @param string $posts Post type to get.
* @param string $terms Taxonomy to group by.
* @param integer $count How many post to show per taxonomy term.
*/
function list_posts_by_term( $posts, $terms, $count = -1 ) {
$tax_terms = get_terms( $terms, 'orderby=name');
foreach ( $tax_terms as $term ) {
echo '<h2>' . $term->name . '</h2> <ul>';
$args = array(
'posts_per_page' => $count,
$terms => $term->slug,
'post_type' => $posts,
);
$tax_terms_posts = get_posts( $args );
foreach ( $tax_terms_posts as $post ) {
echo '<li><a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a></li>';
}
echo '</ul>';
}
wp_reset_postdata();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment