I am using this to randomize the rows of a repeater field. This technique worked a while back on another site a long time ago. However on this site I am getting the output, just not randomized. Any help is greatly appreciated.
<?php
$repeater = get_field('contributors_grid','option');
$count = count(get_field('contributors_grid','option'));
$random_rows = array_rand($repeater, $count);
if(is_array($random_rows)) {
foreach( $random_rows as $random_row ){ ?>
<li class="item">
<a href="<?php echo $repeater[$random_row]['contributors_link'] ?>" target="_blank">
<img src="<?php echo $repeater[$random_row]['contributors_image'] ?>" alt="<?php echo $repeater[$random_row]['contributors_title'] ?>" />
<div class="name"><?php echo $repeater[$random_row]['contributors_title'] ?></div>
</a>
</li>
<?php }
}
?>
Note: I tried Elliot’s shuffle method from another thread too and that didn’t work either.
Regards,
John
What’s being returned by
$repeater = get_field('contributors_grid','option');
// try echoing it to see it it's an array
echo $repeater;
There are times when this might return an array, but there are other times when it will just return the number of rows in the repeater. It is unclear to me why there is inconsistent behavior like this when getting a repeater.
You may need to loop through the repeater to get the values before you can randomize them.
Hi John:
I tried echoing and its says Array. Any idea on how to proceed?
Regards,
John
I’ve actually never used array_rand before so I did some testing. Basically what I found was that no matter how many items you want returned, the keys are always returned in order. So it you pick 3 of 5
you might get 0, 2, 4
but never 4, 0, 2
. So when selecting the 5 of 5
it will always return 0, 1, 2, 3, 4
shuffle is what you’re looking for
$repeater = get_field('contributors_grid','option');
shuffle($repeater);
The topic ‘Randomize Repeater Rows…’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.