Get random page based on tag + get a random image from this page + resize image

Hi all,

I’ve been struggling with this one for a while now and it may well be down to the fact that I’m no php or even kirby expert… But will have to ask anyhow.

I’m using the following code to draw in random images site wide from their associated tags where the $tag is variable

$newtag = $site->index()->visible()->filterBy('categorytags', $tag, ',')->shuffle()->first()->images()->shuffle()->first();

Because I’m drawing in quite a lot of images through this by looping it I need to downsize all the images quite significantly so I’m attempting to then resize these using the thumb() method. The above code works fine for drawing in the full size images. But then upon using the thumb method like beneath i get an error message:

echo thumb($newtag, array('width' => 300));

The error message:
Method Thumb::__toString() must return a string value

Which I’m guessing means its something to do with the image object. I’ve tried using toFile() and a few other methods with no luck and don’t quite understand where its going wrong so any help would be much appreciated!

Max

What about using this method?
https://getkirby.com/docs/cheatsheet/file/thumb

<?php 
  if ($newtag) {
    echo $newtag->thumb(['width' => 300])->html();
  }
?>

But I’m not sure what happens, if the selected page doesn’t have an image. Maybe we should filter only for pages with images … [untested]

<?php 
  // find pages with tag + images
  $pagesWithImage = $site->index()->visible()->filterBy('categorytags', $tag, ',')->filter(function($child) {
                      return $child->hasImages();
                    });

  // pick random page + random image
  if ($pagesWithImage->count()) {
    $newtag = $pagesWithImage->shuffle()->first()->images()->shuffle()->first();
  }

  // resize image
  if ($newtag) {
    echo $newtag->thumb(['width' => 300])->html();
  }
?>
1 Like

Amazing… that worked immediately. Thank you so much. I completely missed that method. Out of interest what is the difference between using that and the other thumb method I was attempting to use? Why did one work and not the other?

Max

Normally, they should to the same … to be honest … I don’t know.

Maybe you picked the pages without images while testing? So the filter has been the real issue and not the thumb method?!

But I’m glad it works know.

1 Like