How to Increment ID value within ACF Repeater Field Loop

The code below is meant to display an Advanced Custom Fields Repeater field.

I need to have unique values for the “for” attribute of the Label tag, and for the ID value of the trailing checkbox input field.

Read More

Also, in order for the field label to work correctly, I need the “for” value to match the ID value of the input field, and each value needs to be unique for each time the field is repeated or displayed on the front end.

See how this displays currently on the front end in the source:
Imgur

The ID and “for” value are blank, but need to be matching values for each row of fields, but also needs to be unique per row.

<?php
if ( get_field('ingredients-list') )
{
    echo '<ul class="ingredientsList">';
    while ( has_sub_field('ingredients-list') )
    {
    echo '<li class="ingredient" itemprop="ingredients"> <label for=""> <input type="checkbox" class="check" id=""> ';
            if ( get_sub_field('quantity') ) echo '<span class="quantity">' . get_sub_field('quantity') . '</span> ';
            if ( get_sub_field('measurement') ) echo '<span class="measurement">' . get_sub_field('measurement') . '</span> ';
            if ( get_sub_field('ingredient_name') ) echo '<span class="name">'. get_sub_field('ingredient_name') .'</span>';
            if ( get_sub_field('measurement') ) echo '<span class="notes">' . get_sub_field('notes')  . ' </span>';
        echo '</label>';
    echo '</li>';
}
echo '</ul>';

}
?>

Related posts

Leave a Reply

2 comments

  1. Try using a “counter” variable for the loop maybe?

    <?php
    if ( get_field('ingredients-list') )
    {
        echo '<ul class="ingredientsList">';
        $count=0;
        while ( has_sub_field('ingredients-list') )
        {
            echo '<li class="ingredient" itemprop="ingredients"> <label for="check-'. $count .'"> <input type="checkbox" class="check" id="check-'. $count .'"> ';
                if ( get_sub_field('quantity') ) echo '<span class="quantity">' . get_sub_field('quantity') . '</span> ';
                if ( get_sub_field('measurement') ) echo '<span class="measurement">' . get_sub_field('measurement') . '</span> ';
                if ( get_sub_field('ingredient_name') ) echo '<span class="name">'. get_sub_field('ingredient_name') .'</span>';
                if ( get_sub_field('measurement') ) echo '<span class="notes">' . get_sub_field('notes')  . ' </span>';
            echo '</label>';
            echo '</li>';
            $count++;
        }
    echo '</ul>';
    }
    ?>
    
  2. This sounds more like a php question, but you might try

    <?php $uniqid = uniqid('item_');?>
    

    to generate an unique string of the form

    item_4b3403665fea6
    

    and your html would look like:

    <label for="item_4b3403665fea6"> 
    <input type="checkbox" class="check" id="item_4b3403665fea6">
    

    You can read more about it here in the PHP documentation:

    http://php.net/uniqid