Filter images by field value

Hello,

I intend to display landscape images differently than portrait images. Using the EXIF data, Kirby can determine which orientation an image has. My problem is that some images have no or incorrect information in this regard. For this reason, when uploading, a separate select field allows the users to set the orientation themselves. How can I filter images based on this select field in a template? The filter doesn’t work yet and calls all images. The template below is a snippet. Its $image variable is defined in the page template.

Blueprint:

title:  Images

accept:
  extension: jpg, png, gif
fields:
  orientation:
    type: select
    options:
      - portrait
      - landscape

Snippet:

<?php if ($image->filterBy('orientation', 'portrait')): ?>
<img class="portrait" src="<?= $file->url() ?>" alt="<?= $file->alt() ?>">
<?php else: ?>
<?= $image ?>
<?php endif ?>

What is $image? You can filter a files collection not a single file object, for example:

$files = $page->images()->filterBy('orientation', 'portrait');
1 Like

Page template:

<?php if ($page->files()->isNotEmpty()): ?>
<?php foreach ($page->files()->filterBy('type', 'in', ['image', 'video', 'audio'])->sortBy('sort', 'asc') as $file): ?>
<figure>
  <?= snippet($file->type(), ['file' => $file]) ?>
  <?php if ($file->caption()->isNotEmpty()): ?>
  <figcaption>
    <?= $file->caption()->kirbytext()  ?>
  </figcaption>
  <?php endif ?>
</figure>
<?php endforeach ?>
<?php endif ?>

Image snippet:

<?php if ($file->orientation()->value('portrait')): ?>
<img class="portrait" src="<?= $file->url() ?>" alt="<?= $file->alt() ?>">
<?php else: ?>
<?= $file ?>
<?php endif ?>

I just want to determine if the select field value is portrait or not. It doesn’t work yet.

<?= $file->orientation() ?> returns it, for instance.

In your topic headline you say you want to filter images by orientation. That is something else than checking if an image’s orientation is portrait.

To check an images orientation use:

<?php if ($image->isPortrait()) : ?>

Dear @pixelijn,

yes, this was my first attempt. It worked perfectly for images with correct EXIF data:

Using EXIF data, Kirby can determine which orientation an image has. My problem is that some images have no or incorrect information in this regard. For this reason, when uploading, a separate select field allows the users to set the orientation themselves [in the panel]. How can I filter images based on this select field in a template?

Please see the screenshot below. It shows the problem.

That’s why I create a workaround using a select field. Unfortunately, it’s still not working.

<?php if ( $file->content()->orientation()->value() === 'portrait') : ?>
1 Like

Thanks, that’s it!

Image snippet:

<?php if ( $file->content()->orientation()->value() === 'portrait') : ?>
<img class="portrait" src="<?= $file->url() ?>" alt="<?= $file->alt() ?>">
<?php else: ?>
<?= $file ?>
<?php endif ?>