Support

Account

Home Forums Add-ons Repeater Field Unique ID for Repeater Field Reply To: Unique ID for Repeater Field

  • Don’t use uniqid() with the same input and expect different output on consecutive calls within a for/while loop—see https://www.php.net/manual/en/function.uniqid.php#120123.

    The uniqid() function is part of the standard PHP library and has no relation or knowledge of ACF, and so does not in any way set “a variable by pulling the ACF unique ID of a repeater in a flex block” as @pierrebalian claims. It simply outputs a “random” string based on the current microseconds and any seed you feed it.

    If you must use uniquid() at least feed it some value from your repeater within the loop so that you can reasonably expect it to be different each time. Both @pierrebalian and @waynep16 are generating a single random string once and outputting it within the loop, which will obviously output the same value each time.

    The better option is to use a hashing function like md5() along with serialize() to not only generate unique strings, but also ensure that they are the same id each page load. This method creates a hash for the full repeater/flexible content field row. You can also use substr() to reduce the length to something manageable, like 8 characters, and still be reasonably sure that you’ll get unique values each time.

    
    <?php
    $rows = array();
    while ( have_rows( 'repeater_or_flex_content' ) ) : $row = the_row(true); // pass true to get formatted subfields
    	$id = substr( md5( serialize( $row ) ), 0, 8 ); // outputs something like '35f841ff'
    	$rows[$id] = $row; // store the $row for use elsewhere with the id
    ?>
    	<div id="panel-<?php echo $id; ?>" aria-labeledby="tab-<?php echo $id; ?>" role="tabpanel">
    		<?php the_sub_field( 'tab_content' ); ?>
    	</div>
    <?php
    endwhile;
    
    // Later, when building tabs
    foreach ( $rows as $r ) :
    ?>
    	<button id="tab-<?php echo $r['id]; ?>" role="tab" aria-controls="panel-<?php echo $r['id']; ?>"><?php echo $r['tab_title']; ?></button>
    <?php
    endforeach;
    

    Of course you can reverse this approach so you’re outputting tabs first, storing the rows, and using them later to output the tab content, but hopefully you get the gist.