Support

Account

Home Forums ACF PRO Can I create a loop to build a query for all meta key/value pairs?

Solving

Can I create a loop to build a query for all meta key/value pairs?

  • 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.

  • Hi @steven

    I believe your second setup is better than the first. With your first setup, you need to get all of the counties first. It depends on the field type of the counties. If it’s a text, you need to get them using wpdb class.

    I hope this makes sense.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Can I create a loop to build a query for all meta key/value pairs?’ is closed to new replies.