Home Forums General Issues nested relationship query


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:

                    // 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()) {
                            // get projects
                            $posts = get_field('projects');
                            if ($posts): ?>
                                    <?php foreach ($posts as $post): // variable must be called $post (IMPORTANT) ?>
                                        <?php setup_postdata($post); ?>
                                            <a href="<?php the_permalink(); ?>">
                                                <?php the_post_thumbnail(); ?>
                                                <?php the_title(); ?></a>
                                            $stylists = get_field('stylists', $post);
                                            if ($stylists): ?>
                                                    <?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; ?>
                                            <?php endif; ?>
                                    <?php endforeach; ?>
                                <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
                            <?php endif;
                    // Restore original Post Data

    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

    What you’re going to need to do is loop over projects the same way that you’re looping over stylists.

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

The topic ‘nested relationship query’ is closed to new replies.