First image from all page children

hi —

having issues pulling only the first images from all my page children;

any help would be sweet;

<?php foreach($page->children()->visible() as $subpage): ?>
<?php foreach($subpage->images()->first() as $bb): ?>
<img src="<?php echo $bb->url(); ?>"/>
<?php endforeach ?>
<?php endforeach ?>
1 Like

The second foreach loop is not needed because you only want to fetch a single image:

<?php foreach($page->children()->visible() as $subpage): ?>
  <?php if($image = $subpage->images()->first()): ?>
    <img src="<?php echo $image->url(); ?>"/>
  <?php endif ?>
<?php endforeach ?>
2 Likes

amazing thank you. not sure whats happening with the first() function but it seems to pull the last image on some of the children pages. any idea what could be causing this?

I guess it depends on the sorting of your images,
you could sort alphabetically or by date created… If you want a specific image i would look at the image field

https://getkirby.com/docs/cheatsheet/panel-fields/image

and in your template (coverImage, since the field’s name is coverImage in the if statement)

In blueprints/pagetemplate.yaml add:

fields:
  coverImage:
    label: Cover Image
    type: image

In templates/pagetemplate.php

<?php foreach($page->children()->visible() as $subpage): ?>
  <?php if($image = $subpage->coverImage()): ?>
    <img src="<?php echo $image->url(); ?>"/>
  <?php endif ?>
<?php endforeach ?>
1 Like