Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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();
}
@Irfan-Ansari

This comment has been minimized.

Copy link

Irfan-Ansari commented Jan 23, 2014

Hey Jared Cornwall,

Here is the bug free code:

/**
* 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();
}
@jaredkc

This comment has been minimized.

Copy link
Owner Author

jaredkc commented Apr 7, 2015

Thanks

@lucasloyola

This comment has been minimized.

Copy link

lucasloyola commented Nov 17, 2015

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

@Wadizorg

This comment has been minimized.

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
You can’t perform that action at this time.