0

I have a gallery field created with Advanced Custom Fields. My code spits out all the images on a page. So far so good. I would like all the images to load in random. I tried to use shuffle() and array_rand(). That works fine, it loads my images in random order. My issue is duplicates. I have a handful of images and I can see duplicate images being loaded.

My current code:

<?php while ( have_posts() ) : the_post(); ?>
<?php $images = get_field('gallery');
// thumbnail
if( $images ): ?>
<ul id="container" class="tiles-wrap animated">
<?php array_rand($images); ?> //I tried shuffle($images)
    <?php foreach( $images as $image ): 
       // $rand_class = array('small', 'medium', 'large');
    $size = 'medium';
$thumb = $image['sizes'][ $size ];
$width = $image['sizes'][ $size . '-width' ];
$height = $image['sizes'][ $size . '-height' ]; ?>

   <li><img src="<?php echo $image['sizes']['medium']; ?>" alt="<?php echo $image['alt']; ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" /></li>       

    <?php endforeach; ?>
<?php endif; ?>
</ul>
    <?php endwhile; // end of the loop. ?>

Thank you in advance.

closed as off-topic by Mark Kaplun, Pat J, Pieter Goosen, Mayeenul Islam, Robert hue Apr 21 '15 at 12:25

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    Close voted as this is a php question or a plugin question. – Mark Kaplun Apr 20 '15 at 16:13
1

Use array_unique() before foreach:

Edited:

<?php while ( have_posts() ) : the_post();

    $images = get_field('gallery');

    // thumbnail
    if( $images ): 
?>
    <ul id="container" class="tiles-wrap animated">
        <?php 
            $images = array_rand($images); 
            $images = array_unique($images); 

            foreach( $images as $image ): 

                // $rand_class = array('small', 'medium', 'large');
                $size = 'medium';
                $thumb = $image['sizes'][ $size ];
                $width = $image['sizes'][ $size . '-width' ];
                $height = $image['sizes'][ $size . '-height' ]; ?>

               <li><img src="<?php echo $image['sizes']['medium']; ?>" alt="<?php echo $image['alt']; ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" /></li>       

            <?php endforeach;
       endif; ?>
    </ul>
<?php endwhile; ?>
  • Since this thread is closed, Ill try the above. Thank you Theme20. – user1457514 Apr 22 '15 at 18:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.