Support

Account

Home Forums Front-end Issues Repeated Relationship Fields and $post

Solved

Repeated Relationship Fields and $post

  • Hi,

    I ran into an issue tonight that I think has to do with the global $post variable but I’m not sure. I have a repeater with some conditional logic. Depending on a checkbox, it’ll allow you to pick “resources” from internal posts/pages via relationship field, external links (text) or media uploaded docs(file). I basically followed the tutorial here: http://www.advancedcustomfields.com/resources/field-types/relationship/#template-usage. The main difference (I think) is that mine was in a repeater.

    Anyway, this didn’t work:

    $internals = get_sub_field('internal_link');
    foreach($internals as $internal):
    	setup_postdata($internal); 
    ?>
    <a href="<?php echo the_permalink(); ?>">
    

    Debugging $internals shows it as a collection of WP Post objects.

    But this did:

    $internals = get_sub_field('internal_link');
    foreach($internals as $post):
    	setup_postdata($post); 
    ?>
    <a href="<?php echo the_permalink(); ?>">
    

    Would someone please explain why?

  • Hi @Will

    If $internals is an array of posts, then the get_sub_field function is working correctly. Perhaps the issue lies in the setup_postdata funciton which can cause many problems wiht the global $post object.

    Try this instead:

    
    $internals = get_sub_field('internal_link');
    foreach($internals as $p): ?>
    <a href="<?php echo get_permalink( $p->ID ); ?>">
    
  • Thanks Elliot. Yes, that works well. I had that going at first but ran into some other wall that got me to look at the docs and try the setup_postdata() route.

    I’ll mark this as solved and file it mentally under ‘setup_postdata function can cause many problems with the global $post object.‘ I’m having other problems on the page now with conditionals and sub_field values which I’ll chalk up to that too! Will retry your suggested method.

  • Follow up: the wall I ran into the first time I tried the non setup_postdata method was that you can’t pass an id to get_the_excerpt(). I rewrote the entire loop without the setup_postdata stuff and made my own excerpt function. All is working swimmingly. Thanks again.

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

The topic ‘Repeated Relationship Fields and $post’ is closed to new replies.