0

I created a gallery with the "gallery add-on" of "advanced custom field" plugin.

I'm trying to show one random image from the gallery on page refresh. Here's my code:

<?php

    $gallery = get_field('gallery_home');           
    $rand = array_rand($gallery, 1);

        if( $rand ): ?>

            <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

<?php endif; ?>

But the result is this:

<img src="" alt="">

Where am I missing something?

1 Answer 1

2

Shouldn't you be doing something like this?

<img src="<?php echo $rand['url']; ?>" alt="<?php echo $rand['alt']; ?>" />

Update

I'm not really familiar with that plugin (stuff could be happening behind the scenes) but here's a better guess than my previous one:

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

if( $gallery ): ?>
    <img src="<?php echo $gallery[$rand]['url']; ?>" alt="<?php echo $gallery[$rand]['alt']; ?>" />
<?php endif; ?>
6
  • Thanks for your response but it outputs the same thing. I've a clue here: stackoverflow.com/questions/13635787/… but I don't really get it. I'm no good with php.
    – kay
    Commented May 16, 2013 at 8:39
  • If you dump $gallery like this var_dump($gallery); – what does it output?
    – Richard B
    Commented May 16, 2013 at 13:24
  • To see The var_dump($gallery); output: pastebin.com/a6xFypQQ
    – kay
    Commented May 16, 2013 at 15:54
  • var_dump($rand); outputs : int(n) where n is a number outputted randomly at each page refresh.
    – kay
    Commented May 16, 2013 at 16:25
  • I've updated my answer.
    – Richard B
    Commented May 16, 2013 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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