1

I’ve found others (source 1, source 2, source 3) using the following code for displaying a random gallery image (and it works) with the ACF Plugin:

<?php
$gallery = get_field('images');
$rand = array_rand($gallery, 1);

if( $gallery ): ?>
    <img src="<?php echo $gallery[$rand]['sizes']['large']; ?>" alt="<?php echo $gallery[$rand]['alt']; ?>" />
<?php endif; ?>

But I’m trying to do it with wp_get_attachment_image() (for responsive images) but not sure how to get the $rand variable working? The ACF Documentation for the Gallery field has a 'Basic List of Images" example that uses wp_get_attachment_image() but I'm not needing to loop through the gallery.

Any help would be greatly appreciated. I think it has to be something like the following, with the $rand variable added somewhere:

<?php 
    $images = get_field('gallery');
    $size = 'full'; // (thumbnail, medium, large, full or custom size)
    $rand = array_rand($images, 1);

    if( $images ): ?>
            <?php echo wp_get_attachment_image( $images['ID'], $size ); ?>
<?php endif; ?>
2
<?php 
    $images = get_field('gallery');
    $size = 'full'; // (thumbnail, medium, large, full or custom size)
    $rand = array_rand($images, 1);

    if( $images ): ?>
            <?php echo wp_get_attachment_image( $images[$rand]['ID'], $size ); ?>
<?php endif; ?>

This code should work. array_rand() return key if second param set to 1 or array with keys if second param > 1

  • Thanks. This does work. But I received an answer on the ACF forums (I had posted there first but was not getting any responses, which is why I came to StackExchange) that explained adding a false parameter will return raw/unformatted value and therefore does not required ACF having to do all the queries involved to get all that image data that will not be used. I've added this now as an answer (and will accept is as selected answer in 2 days when I can) for anyone looking for this solution in the future. – codeview Feb 6 '18 at 22:08
1

Answer found via ACF Forums. Adding the false parameter returns raw/unformatted value.

<?php 
    $images = get_field('gallery', 'option', false); // Adding the `false` parameter returns raw/unformatted value
    $size = 'full'; // (thumbnail, medium, large, full or custom size)
    $rand = array_rand($images, 1);

    if( $images ): ?>
        <?php echo wp_get_attachment_image( $images[$rand], $size ); ?>
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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