Home Forums General Issues while ( have_rows() ) within while ( have_rows() )


while ( have_rows() ) within while ( have_rows() )

  • I’m creating a slideshow with a layout that is driving me a bit crazy. I have three slides with an image, header and description each. When slide #1 is shown, the header and description from all three slides should be visible within the first slide. How can I create a nested loop like that? Using a while within a while would cause an infinite loop.

    This is essentially what I would like to do:

    <?php if( have_rows('slide') ): ?>
    	<div class="slides">
    				<?php while( have_rows('slide') ): the_row(); ?>
    					<div class="slide-container">
    							<div class="slide">
    								<?php echo $image; ?>
    								<?php echo $header; ?>
    							<div class="all-slides"> 
    								<?php while( have_rows('slide') ): the_row(); ?> // loop through all slides each time
    										<div class="all-slides-info">
    											<?php echo $header; ?>
    											<?php echo $description; ?>
    								<?php endwhile; ?>
    				<?php endwhile; ?>
    <?php endif; ?>

    The reason I can’t use two separate loops is that the second section needs to contained within the slide-container div for the layout to work. Very grateful for any suggestions!

  • You’ve got the answer, you can’t.

    To do this you really need to forget about using the ACF have_rows() loops and instead get the contents of the repeater and use the array it returns

    // return all the contents of the repeater in a nested array
    $slides = get_field('slide');
    // loop over array
    if ($slides) {
      foreach ($slides as $slide) {
        // output information from this slide
        foreach ($slides as $inner) {
          // output nested slide information
        } // end nested foreach
      } // end outer foreach
  • Okay, thank you! I see how this works. Stupid question: how do I get the sub fields in the foreach loops? Get_sub_field och get_field doesn’t seem to do the trick.

  • The sub fields are part of the array you get back when you use get_field(). To see what’s in it

    $slides = get_field('slide');
    echo '<pre>'; print_r($slides); echo '</pre>';
  • Thank you! Got everything up and running now!

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

The topic ‘while ( have_rows() ) within while ( have_rows() )’ is closed to new replies.