I have a main CPT ‘event’ and another CPT ‘venue’. In my ‘event’ CPT I have a relationship field ‘event_venue’ which grabs the relevant ‘venue’ for each ‘event’.
Using a custom WP_Query for my main loop, I’m showing data from the ‘event_venue’ relationship field using this loop within the main loop:
<?php $posts = get_field('event_venue'); // Relationship field
if( $posts ): ?>
<?php foreach( $posts as $post): ?>
<?php setup_postdata($post); ?>
<td>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</td>
<td>
<?php the_field('venue_address', $post->ID); ?> <?php get_field('venue_city', $post->ID); ?><?php if( get_field('venue_state', $post->ID )): ?>, <?php the_field('venue_state', $post->ID); ?><?php endif; ?> <?php the_field('venue_postcode', $post->ID); ?> <?php the_field('venue_country', $post->ID); ?>
</td>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; // end our custom Loop within the loop ?>
That shows the data from the ‘venue’ using the relationship field. The problem is the loop is not being reset even with wp_reset_postdata();
so nothing below that from the main custom query loop is showing.
What am I doing wrong here?
Using the Basic Loop without setup_postdata();
as explained in the Relationship Field documentation ended up working.
Here is the code:
<?php $posts = get_field('event_venue'); // Relationship field
if( $posts ): ?>
<?php foreach( $posts as $p): ?>
<td>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</td>
<td>
<?php the_field('venue_address', $p->ID); ?> <?php get_field('venue_city', $p->ID); ?><?php if( get_field('venue_state', $p->ID )): ?>, <?php the_field('venue_state', $p->ID); ?><?php endif; ?> <?php the_field('venue_postcode', $p->ID); ?> <?php the_field('venue_country', $post->ID); ?>
</td>
<?php endforeach; ?>
<?php endif; // end our custom Loop within the loop ?>
I guess the question now is why the Basic Loop with setup_postdata();
doesn’t work? In any event my issue is solved!