Random background image every refresh

Hello!
I try to set a background image that every time that the page loads it takes a different image from a list of images that the client uploaded through the panel.

in the home page yml I have this section:

  haunt:
    type: fields
    fields:
      imges:
        label: Images for home gallery
        type: files
        layout: cards
        image:
          cover: true

I want to call to one of these images randomly to set it as a background image.
I use this tutorial and this is my code in the page template:

<div class='haunted-background'>
    <img src="<?= page('home')->imges()->shuffle()->first()->toFile()->url()?>" >
</div>

The result that I get is just the first image in the list. nothing random about it :slight_smile:
If I change the order of the images I get the new first image.

Any idea what went wrong?

Thank you!

You want to turn the field value into a files collection first:

<?php
  $images = page('home')->imges()->toFiles()
  $randomImage = $images->shuffle()->first()
?>
<img src="<?= $randomImage->url() ?>">
1 Like

works like a charm :slight_smile:
thanks a lot

Hello Günther,
is it possible to set an if query if no photos have been deposited?

Just like:

<?php if($image = $page->cover()->toFile()): ?>
  <img src="<?= $image->url() ?>" alt="">
<?php endif ?>

Thank you!

Hello Hacke,

doing this should work:

$images = $page->cover()->toFiles();
if($images->count()) {
  // do something with the files
}

Hello Thomas,

thank you. Can you please send the full code with the shuffle function on this?

<?php
  $images = page('home')->imges()->toFiles()
  $randomImage = $images->shuffle()->first()
?>
<img src="<?= $randomImage->url() ?>">

Cheers, Alex

PS: Sorry, i thought your name is Günther

Hey Alex,

<?php
  $images = $page->cover()->toFiles();
  if($images->count()):
?>

<img src="<?= $images->shuffle()->first()->url() ?>">

<?php else: ?>

<!-- Your fallback -->

<?php endif ?>

No worries btw, I’m used to being called Günther :slight_smile:

1 Like

Worked awesome :blush: Thank you so much! :+1:

Here is my full code, if anyone is interested:

<?php
  $images = page('header')->header_fotos()->toFiles();
  if($images->count()):
?>

    <img
         src="<?= $images->shuffle()->first()->crop(1600, 600, 80)->url() ?>"
         srcset="<?= $images->shuffle()->first()->crop(3200, 1200, 55)->url() ?> 2x"
         alt="<?= $images->shuffle()->first()->alt()->kirbytextinline() ?>" class="img-fluid"
    >

    <?php else: ?>

    <img src="<?php echo url('assets/images/header-platzhalter.jpg') ?>" class="img-fluid">

<?php endif ?>