Skip to content

Instantly share code, notes, and snippets.

@jaredkc
Last active April 25, 2024 03:39
Show Gist options
  • Save jaredkc/6191133 to your computer and use it in GitHub Desktop.
Save jaredkc/6191133 to your computer and use it in GitHub Desktop.
Wordpress: 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');
$args = array(
'posts_per_page' => $count,
$terms => $term->slug,
'post_type' => $posts,
);
$tax_terms_posts = get_posts( $args );
foreach ( $tax_terms as $term ) {
echo '<h2>' . $term->name . '</h2> <ul>';
foreach ( $tax_terms_posts as $post ) {
echo '<li><a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a></li>';
}
echo '</ul>';
}
wp_reset_postdata();
}
@lucasloyola
Copy link

Thanks guys, this helped me. I was trying to get 1 post per taxonomy.

@Wadizorg
Copy link

Wadizorg commented Apr 5, 2018

nice and useful/ thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment