Search code examples
phpwordpressrepeateradvanced-custom-fields

How to randomise a list of URL's in PHP using ACF?


I have a web page that calls in 7 images from wordpress using an ACF Repeater field.

What I want to do is get the list of URL's of the images and then shuffle them so that they images will appear randomly on the webpage. When I call the images with ($image['url']) , the only image that is displayed is the last image uploaded to the wordpress site.

<?php       
    // Call the ACF Gallery images 
    $imageArray = get_field('company_logos', 13);
    $size = 'full'; // (thumbnail, medium, large, full or custom size)

    if( $imageArray ):
        while( have_rows('company_logos', 13) ) : the_row();
             $image = get_sub_field('image');
            // $content = get_sub_field('content');

              //shuffle ($image['url']);

              $arr = $image['url'];
              shuffle($arr);
              print_r($arr);

        endwhile;
        endif; ?>

When I echo out the images URL's to the screen they come out in the format of:

http://localhost/wordpress/wp-content/uploads/2016/07/a.jpg
http://localhost/wordpress/wp-content/uploads/2016/07/b.png
http://localhost/wordpress/wp-content/uploads/2016/07/c.jpg
http://localhost/wordpress/wp-content/uploads/2016/07/d.jpg
http://localhost/wordpress/wp-content/uploads/2016/07/e.jpg
http://localhost/wordpress/wp-content/uploads/2016/07/f.jpg
http://localhost/wordpress/wp-content/uploads/2016/07/g.jpg

Anyone know how to do this? Thanks!


Solution

  • Do you get the list of images from $image['url']? Does it return an array in the first place? If it does then your solution should work. If it is not an array but a string of URLs separated by comma then, do the following before the 2nd statement. So, the new code would look like as follows,

    $urls = $image['url'];
    $arr = explode(" ", $urls);
    shuffle($arr);
    print_r($arr);