ACF put a comma after the last repeater field value

I’ve the following code

<?php if(have_rows('ore')):?>

        <?php while( have_rows('ore')): the_row();

                $start = get_sub_field('start');
                $end = get_sub_field('end');
        ?>

         <?php if( get_row_index() != 1 ){ echo '/'; }?>
               <?php echo $start;?> – <?php echo $end;?>    
    
    <?php endwhile;?>
<?php endif;?>

Which outputs the two fields (“start” & “end”) in this form: 12.00 – 13.00.
In case there are more than one, they’ll be displayed like this 12.00 – 13.00 / 15.40 – 16.00 and so on.

How can I put a comma after the last field? (–> 12.00 – 13.00 / 15.40 – 16.00, or even 12.00 – 13.00,)
(I guess I’ve to count the number of rows and when reaching the last one, put the comma …)

Thanks

David

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re generating whitespace because of the blank line between the echo $end block and the endwnile, and because you’re switching in and out of PHP which means everything between the ?> and <?php – i.e. all of the whitespace – will get echoed out. (HTML then merges the blank lines and spaces into a single space for display.)

You can just do this a single PHP block to save switching in and out of PHP, which will prevent any extra whitespace getting echoed:

<?php
if (have_rows('ore')) {
    while(have_rows('ore')) {
        the_row();

        $start = get_sub_field('start');
        $end = get_sub_field('end');

        if( get_row_index() != 1 ) {
            echo '/';
        }
        echo esc_html($start).' - '.esc_html($end);
    }
    echo ',';
}
?>

Note that I’ve also added esc_html() around the $start and $end values as you echo them. I might also check if these were present or not too before using them, unless you’re positive they’ll always have values.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x