tobiasg
tobiasg

Reputation: 1073

Mix post-object with sub fields in ACF

I'm trying to make a loop that lets me display items from a repeater field that has a regular text field (separate from the post-object) and a post-object field on a page. I want to collect the title and the featured image from the post-object and a custom description from the text field.

This is the structure of the repeater field:

highlighted_projects [Repeater]
   selected_projects [Post-object]
   description [Text]

This is the code I have so far that successfully displays the content from the selected post:

<section class="bg-white">
  <?php if( have_rows('highlighted_projects')): // check for repeater fields ?>
    <?php $i = 0; ?>
      <?php while ( have_rows('highlighted_projects')) : the_row(); // loop through the repeater fields ?>
        <div class="grid">
      <?php // set up post object
          $select_project = get_sub_field('select_project');
            if( $select_project ) :
            $post = $select_project;
            setup_postdata($post);
            ?>
            <?php if($i % 2 == 0) : ?>
          <div class="grid__col grid__col--3-of-6"><h3><?php the_title(); ?></h3></div>
          <div class="grid__col grid__col--3-of-6"><?php the_post_thumbnail(); ?></div>
        <?php else : ?>
          <div class="grid__col grid__col--3-of-6"><?php the_post_thumbnail(); ?></div>
          <div class="grid__col grid__col--3-of-6"><h3><?php the_title(); ?></h3></div>
        <?php endif; ?>
        <?php $i++; ?>
          <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
      <?php endif; ?>
      </div>
      <?php endwhile; ?>
  <?php endif; ?>
</section>

But as soon as I put <?php the_sub_field("description"); ?> in the loop, it breaks. I assume that it has to do with the loop trying to find the description field in the post connected to the post-object instead of the repeater itself. Would appreciate any thoughts on how to achieve looping through both the post-object and the associated subfields at the same time.

Upvotes: 1

Views: 447

Answers (1)

Stender
Stender

Reputation: 2492

Before setting up the post object -

$description = get_sub_field('description') 

- right after the

$select_project = get_sub_field('selected_project'); 

Then just echo out $description

Upvotes: 1

Related Questions