Get site images by name partial

Hey all,

the case I try to solve is the following.

I am building a website for a client as a one-pager.
All images will be uploaded as $site elements, so they are easily available everywhere on the website.
The website consist of different sections one of them is called ‘projects’.
I would love to be able to show images in those sections based on a name partial.
For example all images for ‘projects’ are supposed to be named like this:
With this pattern I should be able to get all images with ‘project’ as a partial.
File extensions are only examples, but I basically need to support those three types.

I understand, that I can get all images for $site by doing the following:

<?php foreach($site->images() as $image): ?>
  <img src="<?php echo $image->url() ?>" alt="">
<?php endforeach ?>

What I can not figure out is how to get the images by their name partials.
I tried it with findBy(), which sadly gives me only an error message.

Can someone help me out?
Is this possible with Kirby?

So you want to get every site image that contains the string project? That would be this:

<?php foreach($site->images()->filterBy('name', '*=', 'project') as $image): ?>
  <img src="<?php echo $image->url() ?>" alt="">
<?php endforeach ?>

The findBy method returns a single image that matches your query, while the filterBy method returns a collection of all matching images.

1 Like

Thanks a lot! I did not come across the filterBy method before.
Solved my problem.

I went into the same issue today and I was looking for this exact feature. This helped! :slight_smile:

My case is that I use the same name across pages, but my snippet does not know what extension is used for that image.

In my case I only needed one image that matched that name, so this is also possible:

echo $page->images()->filterBy('name', '*=', 'icon')->first();

As I wrote, use findBy for single files.

I tried this but it does not work.

echo $page->images()->findBy('name', '*=', 'icon');

That’s because findBy() only takes two parameters, $key and $value, no filter operators.

However, for your use case, you do not need the filter operator, if the filename is. always the same:

$image = $page->images()->findBy('name', 'icon');

should do. the job, because name()compares the filename without the extension, while filename()looks for name with extension. You can, however, find all that in the docs.