Display all posts in a custom post type, grouped by a custom taxonomy

I’m working on a member page where I use a custom post type with a custom taxonomy. My custom post type is called member and my custom taxonomy is called member_groups.

I want to list all the members but group them together into their respective groups.

So to be clear, I’ve 35 members divided into 9 groups – so instead of making the same query nine times I want to do it once but group them together, so that Member1, Member4 and Member 11 is grouped together in one group, called “Marketing”.

I’m using WP_Query to retrieve all posts under post type member. I’ve tried different attempts but with no successful result.

How can I achieve that?

7

So, you might consider automating the multiple queries.

First, get the list of terms in your custom taxonomy, using get_terms():

<?php
$member_group_terms = get_terms( 'member_group' );
?>

Then, loop through each one, running a new query each time:

<?php
foreach ( $member_group_terms as $member_group_term ) {
    $member_group_query = new WP_Query( array(
        'post_type' => 'member',
        'tax_query' => array(
            array(
                'taxonomy' => 'member_group',
                'field' => 'slug',
                'terms' => array( $member_group_term->slug ),
                'operator' => 'IN'
            )
        )
    ) );
    ?>
    <h2><?php echo $member_group_term->name; ?></h2>
    <ul>
    <?php
    if ( $member_group_query->have_posts() ) : while ( $member_group_query->have_posts() ) : $member_group_query->the_post(); ?>
        <li><?php echo the_title(); ?></li>
    <?php endwhile; endif; ?>
    </ul>
    <?php
    // Reset things, for good measure
    $member_group_query = null;
    wp_reset_postdata();
}
?>

I can’t see anything particularly wrong with this approach, though it may have a limited ability to scale (i.e. if you have hundreds or thousands of members, or member_group terms, you may see performance issues).

Leave a Comment