Support

Account

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

Solved

Repeated Relationship Fields and $post

    • Will

    • February 10, 2014 at 11:42 pm

    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?

    • Elliot

    • February 11, 2014 at 10:01 am

    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 ); ?>">
    
    • Will

    • February 11, 2014 at 3:16 pm

    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.

    • Will

    • February 12, 2014 at 6:28 am

    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)

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.