Skip to content

Instantly share code, notes, and snippets.

@theodorocaliari
Forked from jaredkc/group-posts-by-terms.php
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theodorocaliari/537fa4eded0d46cc44c0 to your computer and use it in GitHub Desktop.
Save theodorocaliari/537fa4eded0d46cc44c0 to your computer and use it in GitHub Desktop.
<?php
/**
* 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