Support

Account

Home Forums General Issues Hack for Nested Queries

Helping

Hack for Nested Queries

  • There have been many topics started here that deal with loops over relational fields (post object and relationship fields) not working properly. The problem usually ends up having to do with nested queries. What happens if you don’t know if you’re in a nested query? Do you always need to use one of the work-a-rounds that I’ve described before, looping over posts manually and leaving the global $post variable alone, not using wp_reset_postdata(), etc, etc.

    Well, I found another hack around this because I had to. It seems that get_the_exceprt() will not work correctly unless you use setup_post_data() on the post you want to get the excerpt from. It seems that WP always uses the global no matter what you pass this function. I personally would call this a bug….

    But I need to do this in a place where I don’t know if it will be in a nested query or not, so I have to assume that it will be.

    So, on to my solutions. This code is pretty much taken from the docs here with my modification added.

    
    <?php 
      $posts = get_field('relationship_field_name');
      
      if ($posts) {
        // hold the current value of the global, whatever it is
        $global_post = $post;
        ?>
          <ul>
            <?php 
              foreach ($posts as $post) { // variable must be called $post (IMPORTANT)
                setup_postdata($post);
                  ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        <span>Custom field from $post: <?php the_field('author'); ?></span>
                    </li>
                  <?php 
              } // end foreach $posts
            ?>
          </ul>
        <?php 
        // reset the orighinal value of the global $post
        setup_postdata($global_post);
      } // end if posts
    ?>
    
  • Nice. Thanks for sharing.

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

You must be logged in to reply to this topic.

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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.