Home › Forums › General Issues › nested relationship query
Hello, we have the current setup:
Editions are comprised of Projects (Relationship Field), and Projects are done by Stylists (also Relationship field). On our homepage we show the latest edition. So we show all Projects in the Edition, with title and the stylist who did the project. This is our code:
<?php
// WP_Query arguments
$args = array(
'post_type' => array('edition'), 'posts_per_page' => 1
);
// The Query
$edition = new WP_Query($args);
// The Loop
if ($edition->have_posts()) {
while ($edition->have_posts()) {
$edition->the_post();
// get projects
$posts = get_field('projects');
if ($posts): ?>
<section>
<?php foreach ($posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post); ?>
<article>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
<?php the_title(); ?></a>
<?php
$stylists = get_field('stylists', $post);
if ($stylists): ?>
<span>
<?php foreach ($stylists as $s): // variable must NOT be called $post (IMPORTANT) ?>
<a href="<?php echo get_permalink($s->ID); ?>"><?php echo get_the_title($s->ID); ?></a>
<?php endforeach; ?>
</span>
<?php endif; ?>
</article>
<?php endforeach; ?>
</section>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif;
}
}
// Restore original Post Data
wp_reset_postdata();
?>
Listing the projects works, but we get an error message for the connected Stylists. Please advise, thanks.
Your problem is likely due to having multiple nested loops on posts and trying to use wp_reset_postdata() in these loops. See my comment here https://support.advancedcustomfields.com/forums/topic/nested-post-object-fields/#post-48227
What you’re going to need to do is loop over projects the same way that you’re looping over stylists.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
🚨 The 2023 ACF Annual Survey closes tomorrow! This is your last chance to complete the survey and help guide the evolution of ACF. https://t.co/0cgr9ZFOJ5
— Advanced Custom Fields (@wp_acf) May 18, 2023
© 2023 Advanced Custom Fields.
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.