Support

Account

Home Forums Add-ons Repeater Field How to output all repeater fields randomly

Solving

How to output all repeater fields randomly

    • Sammy262

    • September 10, 2013 at 11:16 pm

    Hi there,

    I have set up a gallery page that uses the ACF repeater.
    All the gallery items have been created and the site works fine.

    But my question is, would it be possible to output all these gallery items in a random order each time the site is loaded?

    At the moment I use

    if(get_field('gallery-repeater')){ 
    while(the_repeater_field('gallery-repeater')):

    This goes through each row as long as we have rows. So basically all we would need is the option to load these rows (but all of them not just a portion) randomly each time.

    And if yes, could you point me in the right direction please.

    Thanks in advance.

    • Elliot

    • September 11, 2013 at 5:17 pm

    Hi @sammy262

    This will be possible by using a different technique to loop the repeater field data. Instead of using the_repeater_field, you will need to use a more basic PHP aproach as demonstrated on this page:
    http://www.advancedcustomfields.com/resources/field-types/repeater/
    See example – Taking a more basic PHP aproach.

    After you have stored the value as a variable, but before the loop, you can randomize the rows like so:

    
    shuffle( $gallery )
    

    Good luck!

    Thanks
    E

    • Nuro

    • September 18, 2013 at 1:02 pm

    Something like this might be what you’re looking for:

    <?php
    
          $rows = get_field('repeater');
    
            if($rows) {
    
                echo '<h3>Results</h3>';
                echo '<ul>';
    
                $row_count = count($rows);
                $i = rand(0, $row_count - 1);
    
                while(has_sub_field('repeater')) {
    
                      $field = get_sub_field_object('img_title');
                      $value = get_sub_field('img_title');
                      $label = $field['choices'][ $value ];
    
                      echo '<li><a href="' . $rows[$i]['img'] . '">' . $rows[$i][$lable] . '</a></li>' ;
                      $i++;
    
              }
    
              echo '</ul>'; 
           }
                
    ?>
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.