Outputting Advanced Custom Fields ‘Repeater’ Field in a Random Order
For regular developers of WordPress, you may have heard of the Advanced Custom Fields plugin by now. If you haven’t, I recommend you go ahead and download it right away. Personally it has saved me many man hours of coding and has an excellent, easy-to-use interface that I just love working with.
When setting up new custom fields, alongside the standard field types such as ‘text’, ‘image’ and ‘author’, there is a new field which you can purchase as an add-on which is called a ‘repeater’ field; A field that allows you to repeat a subset of fields multiple times. If you’re reading this post you’ve probably already heard of, and are using, this add-on.
One of the jobs I was tasked with recently was to output the data entered into these ‘repeater’ fields in a random order. The documentation describes very clearly how to output the data in a normal fashion like so:
<?php if(get_field('repeater_field_name')): ?> <ul> <?php while(has_sub_field('repeater_field_name')): ?> <li>sub_field_1 = <?php the_sub_field('sub_field_1'); ?>, sub_field_2 = <?php the_sub_field('sub_field_2'); ?>, etc</li> <?php endwhile; ?> </ul> <?php endif; ?>
By modifying the example above I’ve included below how we would output these fields in a random order:
<?php if(get_field('repeater_field_name')): $repeater = get_field('repeater_field_name'); $random_rows = array_rand( $repeater, 6 ); ?> <ul> <?php foreach ($random_rows as $random_row): ?> <li>sub_field_1 = <?php echo $repeater[$random_row]['sub_field_1']; ?>, sub_field_2 = <?php echo $repeater[$random_row]['sub_field_2']; ?>, etc</li> <?php endforeach; ?> </ul> <?php endif; ?>
You’ll notice that we are passing the number ‘6’ to the array_rand() function above. This means that six random rows will be output. If we only wanted one random row we could change this ‘1’, or we could leave out this parameter altogether if we didn’t want to put a cap on it.