Home Forums General Issues Hack for Nested Queries


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.

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

  • Hello @hube2

    Thanks for this code. I’m having issues to show 2 or more relationship fields within the loop.

    I would like to loop through my Job posts and show something like Jobtitle – Place – Fulltime. When i create the CPT’s Places and Employments and use your code twice (and change the relationship field) it only shows the Place and not Fulltime. It must be something with the query resets.

    Any idea how to solve this?

    Thank you,


  • @mennobouma sorry, but I really can’t figure out what you are trying to do or what could be wrong from your explanation. Can you give me some more details or code you are using?

  • Hello John,

    Thanks for your response. When i copy your code twice in the loop to show two field and only change this:

    $posts = get_field('relationship_field_name');

    I only can see the result of just one field. The second is missing.. Or there is something wrong with my loop :).

    Thank you,

  • You must reset the original post data between the loops. If you don’t then you will be getting the second relationship field from the last post of the first loop instead of the original post shown on the page.

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

The topic ‘Hack for Nested Queries’ is closed to new replies.