Support

Account

Home Forums Front-end Issues Querying with ACF relationship values Reply To: Querying with ACF relationship values

  • If you don’t reset the post data at that point, the next time that a post is refereed to it will be looking at the last post in the previous loop. So if we look at this section of code

    
    
                <?php 
                  
                  // I don't understand why you need this
                  // can probably be removed
                  $this_post = $post->ID;
                  
                  $posts = get_field('doctor_specialties');
                  if ($posts) {
                    foreach ($posts as $post) {
                      setup_postdata($post);
                      ?>
                        <h2 class="related-specialties-title">
                          <a class="doctor-specialty-link" href="<?php 
                              the_permalink(); ?>">More <?php 
                              the_title(); ?> Specialists</a></h2>
                      <?php 
                    } // end foreach $posts
                    // if we don't reset the post data here
                    // the last post used in the above loop
                    // will be used in the get_the_ID()
                    // function call below
                    wp_reset_postdata();
                  } // end if $posts
                  
                  
                  // this is where The Loop used to start
                    
                  $args = array(
                    'post_type' => 'our-providers',
                    'orderby' => 'meta_value',
                    'post__not_in' => array($this_post),
                    'meta_query' => array(
                      array(
                        'key' => 'doctor_specialties', // name of custom field
                        'value' => '"' . get_the_ID() . '"',
                        'compare' => 'LIKE'
                      )
                    )
                  );
    

    'value' => '"' . get_the_ID() . '"', The ID returned will be for the last post in the previous loop and not for the post that’s actually being displayed. The only time it would return the current post ID would be if
    $posts = get_field('doctor_specialties'); returned false.

    Maybe what you really want to do is put the second loop inside the first one, but honestly, I can’t say for sure. There is a lot going on in this template, some of which is hard to follow without understanding how all of these things relate to each other.