Grouping WP query results
-
I have a Custom Post Type called “locations”; I also have custom taxonomies for “country” (e.g. term=USA), “city” (e.g. term=Austin), “state” (e.g. term=Texas), “classification” (e.g. classification = Restaurant). On the “locations” CPT, I select country, city, state, classification by way of ACF lookups.
I’m trying to subdivide results pages to look like the following:
City 1
Classification 1
Location 1
Location 2
Classification 2
Location 1
City 2
etcand
Country 1
State 1
State 2
etc
Country 2
etcI currently have a really ugly multi-loop function that handles some cases on my site, but doesn’t work for the above because they’re more complicated. Is there a more efficient way to this on the query level so that I don’t have to have all these nested loop? If I need to do it through loops, how would I modify the below to account for the above cases?
Example function call that does work:
list_posts_by_term_double_loop($term, $terms, “locations”, “country”, get_query_var(‘term’), “state”);<?php function list_posts_by_term_double_loop($term, $terms, $cpt, $currentterm, $currentslug, $groupterm) { foreach( $terms as $term ) : $args = array( 'posts_per_page' => -1, 'post_type' => $cpt, 'order_by' => 'name', 'order' => 'ASC', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => $currentterm, 'field' => 'slug', 'terms' => $currentslug ), array( 'taxonomy' => $groupterm, 'field' => 'slug', 'terms' => $term->slug ), ), ); $custom_query = new WP_Query( $args ); $myCount = $custom_query->found_posts; $count = 0; while($custom_query->have_posts()) : $custom_query->the_post(); if ($count == 0) { echo "<strong>" . $term->name . "</strong><ul>"; } ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php $count = $count + 1; if ($count == $myCount) { echo "</ul>"; } endwhile; wp_reset_postdata(); // reset the query endforeach; wp_reset_postdata(); } ?>
- The topic ‘Grouping WP query results’ is closed to new replies.