0
votes

I need to add a div around every pair of ACF repeater fields entered. I have this snippet of code which does the job for every three fields. Each time I change the number it makes the next div ID a child of the previous. Any suggestions would be great! Thanks

// check if the repeater field has rows of data
if( have_rows('services') ):
  // loop through the rows of data

  // add a counter
  $count = 0;
  $group = 0;

  while ( have_rows('services') ) : the_row(); 
    // vars
    $teacher_bio = get_sub_field('service_title');
    $teacher_name = get_sub_field('service_information');
    $teacher_image = get_sub_field('icon');
    if ($count % 3 == 0) {
      $group++;
      ?>
        <div id="services-<?php echo $group; ?>" class="cf group-<?php echo $group; ?>">
      <?php 
    }
    ?>
    <div class="service">
      <img src="<?php the_sub_field('icon'); ?>" />
      <p><?php echo $teacher_name; ?></p>
      <?php echo $teacher_bio; ?>
    </div><!-- .teacher -->
    <?php 
      if ($count % 3 == 2) {
        ?>
          </div><!-- #services -->
        <?php 
      }
      $count++;
    endwhile;
else :
  // no rows found
endif;
2
could this not be easier, if you just had a repeater inside your repeater? then there would be a row for each "teacher/service" and you could wrap that in any html you wanted - Stender

2 Answers

0
votes

You can do this easily using custom jquery.

0
votes

You're modulus function is incorrect. Use the % 2, as you want to check every two loops. Use 0 at the starting div and 1 for the closing div.

I've created a quick example for you:

<?php

$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$count = 0;

foreach ($arr as &$value) {

    if ($count % 2 == 0) {
        echo '<div>';
    }

    echo $value;


    if ($count % 2 == 1) {
        echo '</div>';
    }

    $count++;

}

Results in: <div>12</div><div>34</div><div>56</div><div>78</div><div>910</div>