Hopefully my title will get across what I’m after.
Here’s the scoop:
There’s a spot on the homepage that lists the “Service Area” of the client. This is shown as lists of towns with headers showing which county each list belongs to.
I created a custom post type service-area so the client will eventually be able to add/remove service areas as needed in the future. Each post represents a “city” and in each post they select which county this city belongs to (this is the sa_county custom field).
I came up with this block of code to display a single “county service area”:
<?php /** BLUE EARTH **/
$args = array(
'numberposts' => -1,
'post_type' => 'service-area',
'meta_key' => 'sa_county',
'meta_value' => 'Blue Earth'
);
$the_query = new WP_Query( $args ); ?>
<?php if( $the_query->have_posts() ): ?>
<div class="grid-item">
<strong>Blue Earth</strong>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<?php the_title(); ?>
</li>
<?php endwhile; ?>
</ul>
</div>
<?php endif; ?>
<?php wp_reset_query(); ?>
The problem here, is that I have the meta_key and meta_value hard-coded into this block of code. There are eight total counties right now. That means eight total service area lists. I know I’m not a great programmer, but I know enough to know that having eight nearly identical blocks of code is just plain stupid.
I apologize for the newbie question, but how can I automate and make this nice and DRY?
Thanks!
Okay, I realized I could simply everything by making a few small changes. Instead of making each ‘town’ into a post, I deleted them all and turned each ‘county’ into a post. Then I added a repeater field, so the user creates a list of towns in each county. Pretty simple fix!
That being said, I’m still curious if my original question is even possible and/or even recommended ever.

The topic ‘Can I create a loop to build a query for all meta key/value pairs?’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.