Support

Account

Home Forums General Issues Multiple relationship fields outside of main loop

Solving

Multiple relationship fields outside of main loop

  • I am trying to use the relationship field outside of the main loop. See relationship code below:

    <?php
    
    global $post; // Needed for use inside a widget
    $posts = get_field('related_posts');
    if($posts):
    							
    $i = 1; ?>
    
    <li class="parent"><a href="#">Related Articles</a>
    <ul class="related-posts">
    <?php foreach($posts as $post): // variable must be called $post (IMPORTANT) ?>
    
    <?php setup_postdata($post); ?>
    <li class="related_post-<?php echo $i; ?>">
    <div class="col-md-4">
    <?php if(has_post_thumbnail()) { ?>
    <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
    <?php }; ?>
    									</div>
    <div class="col-md-8">
    <h4 class="post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
    <?php custom_excerpt(75); ?>
    </div>
    </li>
    <?php $i++; endforeach; ?>
    </ul>
    </li>
    
    <?php wp_reset_postdata();
    
    endif; ?>

    I have to set the global $post at the top of this to make it work outside of the loop. For some reason if I setup another relationship field underneath this one it does not work. Can someone explain to me why this is and how to make it so I can have multiple relationship fields working outside of the main loop.

    Many thanks

  • Not 100% sure but, being the get_field() is a global function you MIGHT have to specifically target the post your are getting the related fields from…

    Maybe doing something like the following would work

    global $post;
    $post_id = $post->ID;
    $posts = get_field( "related_posts", $post->ID );
    

    I’m assuming your above code displays the relationship data properly. Please post the code that is NOT working.

  • The relationship field is pulling in the data from the page that I am on, which is correct. My issue comes if I duplicate the code above and paste it below it (to have 2 instances of the same code), I would assume that the same data would appear below, but that 2nd instance does not appear.

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

The topic ‘Multiple relationship fields outside of main loop’ is closed to new replies.