Search code examples
phpwordpressadvanced-custom-fields

Nested Wordpress Post Object loops with Advanced Custom Fields


I'm looking to display a post object inside another post object.

This is useful to display content (that is containing post objects) from one page on another.

I expect this could be something that is not working with the repeated wp_reset_postdata.

Thankful for any ideas and suggestions.

<?php $post_object = get_sub_field('first-loop');
if( $post_object ): 
    $post = $post_object;
    setup_postdata( $post ); ?>

        <?php $post_object = get_sub_field('second-loop');
        if( $post_object ): 
            $post = $post_object;
            setup_postdata( $post ); ?>

                <!-- advanded custom fields -->

            <?php wp_reset_postdata();?>
        <?php endif; ?>

    <?php wp_reset_postdata();?>
<?php endif; ?>

Solution

  • I got help from the Advanced Custom Fields support (thank you Patrick!) and the solution is as follows. This is a loop on a single-book [custom post] that contains a custom field which is a post-object that fetches content from another a custom post (seller) that lists a series of post-objects (books).

    <?php  $post_object = get_field('post-object'); 
    if( $post_object->ID ): ?>
            post-object title: <?php echo $post_object->post_title; ?>
            <?php if( have_rows('books', $post_object->ID) ):?>
                <?php while ( have_rows('books', $post_object->ID) ) : the_row();?>
                    <?php  $book = get_sub_field('book');
                    if( $book->ID ): 
                    ?>
                    Title: <?php echo($book->post_title); ?>
                    <?php echo($book->cover ); ?>
                    <?php $image = get_field('cover' , $book);
                    if( !empty($image) ): ?>
                        <img src="<?php echo $image['sizes']['medium']; ?>" alt="<?php echo $image['alt']; ?>" />
                    <?php endif; ?>
                    <?php endif; ?> 
                <?php endwhile;?>
            <?php endif;?>
        <?php wp_reset_postdata(); ?>
    <?php endif; ?>