Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change output last item in loop (ACF)

I'm still learning php, but can't get my head on this one.

For a loop in Wordpress I want to output a list with places, seperated with a comma and ending with a point.

Here's my code:

<?php if ( have_rows('subplaats') ): ?>
    <section id="subplaats">
        <div class="subplaats-container">
            <h3 class="support">Wij bestrijden ook in...</h3>
            <p>
                <?php while( have_rows('subplaats') ): the_row(); ?>
                    <?php $plaats = get_sub_field('plaats'); ?>
                    <?php echo $plaats; ?>,
                <?php endwhile; ?>
            </p>
        </div>
    </section>
<?php endif; ?>

Could anyone tell me how to accomplish this? I'm using Advanced Custom Fields. Am I also doing right on hierarchical level?

like image 450
Falch0n Avatar asked Mar 22 '16 09:03

Falch0n


Video Answer


1 Answers

You need to count the total fields in the repeater:

count(get_field('subplaats'));

then have a field counter to check if the current "counted" field is the last one.

I edited and tested your code and It's working good:

<?php
      if (have_rows('subplaats')):
              $all_fields_count = count(get_field('subplaats'));
              $fields_count = 1;
?>
<section id="subplaats">
       <div class="subplaats-container">
            <h3 class="support">Wij bestrijden ook in...</h3>
            <p>
            <?php
                 while (have_rows('subplaats')): the_row();
                        $plaats = get_sub_field('plaats');
                         echo $plaats;
                        if ($fields_count == $all_fields_count) {
                            echo ".";
                        } else {
                            echo ", ";
                        }
                        $fields_count++;
                 endwhile;
            ?>
            </p>
       </div>
</section>
<?php
      endif;
?>

Cheers!

like image 67
Maroun Melhem Avatar answered Sep 19 '22 17:09

Maroun Melhem