0

I have a custom post type set up with Advanced Custom Fields. I would like to display and order my posts in groups. The groups are states of the United States, so I have 50 groups.

Should I perform one query per state or is there a way to create one query that will cycle through all the different ( key : value ) (states) values and echo them out to the page in their respective groups?

    <?php 

        $posts = get_posts(array(
          'posts_per_page'  => -1,
          'post_type'     => 'school',
          'meta_key'    => 'state',
          'meta_value'  => 'Texas'
        ));

        if( $posts ): ?>

          <?php foreach( $posts as $post ): setup_postdata( $post ) ?>
            <li>
              <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            </li>
          <?php endforeach; ?>
        <?php wp_reset_postdata(); ?>
      <?php endif; ?>

This is the standard ACF query by meta value.

0

One option is to fetch all of the posts to a single array and filter that array 50 ways. This would only generate the one query:

$posts = get_posts(array(
      'posts_per_page'  => -1,
      'post_type'     => 'school'
    ));

To filter your array you would do something like this:

$this_state = "Texas";
$state_posts = array_filter($posts, function($results) use($this_state) {
                            return $results['state'] == $this_state;
                            }); 

From there, $state_posts should contain a subset of $posts where the State is Texas. Modify appropriately for each of your 50 groups.

This is untested but modeled on a very similar template I wrote last week.

  • Could you share the template? – Josh Smith Jul 22 '15 at 16:20
  • Send me an email and I can respond with the script. – jdm2112 Jul 22 '15 at 16:27
  • joshuamsmith01@gmail.com – Josh Smith Jul 22 '15 at 16:32
  • You don't have contact info in your profile, but I do. – Josh Smith Jul 22 '15 at 16:35
  • Were you able to make any headway on this? – jdm2112 Jul 23 '15 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.