I have a custom query to show people working in a specific division (label) in an organisation. I want to display the specific division’s name before the cards of the people are displayed. Currently I have this wp_query that filters out the divisions and shows the people in alphabetic order based on their last name. All people are displayed one after the other until the loop ends. What I am looking for is a way to get the division name and show the people, and then the second division and show the people working there etc. There are 7 divisions in total. My working code so far for the custom wp_query:
$all_query = new WP_Query(array(
'post_type' => 'collegas',
'posts_per_page' => -1,
'meta_query' => array (
'relation' => 'AND',
'label' => array (
'key' => 'medewerker_werkzaam_bij',
),
'persoon' => array (
'key' => 'medewerker_achternaam',
),
),
'orderby' => array (
'label' => 'ASC',
'persoon' => 'ASC',
)
));
As you can see, I am ordering by division (‘label’) and then by lastname (‘persoon’). This works great. But how can I check if the name (or value) for the division changes so I can add a heading like before I show the people working there.
This is the loop:
if ( $all_query->have_posts() ) {
?>
<h2 id="opmeer" class="">Iedereen</h2>
<div class="<?php echo $column_class; ?>">
<?php
// Start the loop.
while ( $all_query->have_posts() ) {
$all_query->the_post();
get_template_part( 'loop-templates/content-collegas', get_post_format() );
}
} else {
get_template_part( 'loop-templates/content', 'none' );
}
I want the loop to output a structure like this:
-- Division Name 1 ---
Person 1
Person 2
Person 3
-- Division Name 2 ---
Person 1
Person 2
-- Division Name 3 ---
Person 1
Person 2
Person 3
Person 4
Person 5
etc.
Maybe I need a foreach loop to get this done, but I'm stuck at how to set that up. Any help is appreciated.