Get image from custom image field

Hi guys,

any idea why this code is not working?

<?php foreach($page->children()->visible()->flip() as $newsarticle): ?>
  <div class="news-image">
  	<?php $newsarticle->image($newsarticle->newsimage())->url();  ?>
  </div>
<?php endforeach ?>

I am trying to get the image of a new image field which I named ‘newsimage’.
I read some threads on this and tested codes out, but nothing worked…

Thanks in advance!

Do you get an error message?

In any case, you need an if statement here, otherwise you will get an error in case the image doesn’t exist.

<?php foreach($page->children()->visible()->flip() as $newsarticle): ?>
<?php if($image = $newsarticle->newsimage()->toFile()): ?>
  <div class="news-image">
  	<?= $image->url();  ?>
  </div>
<?php endif ?>
<?php endforeach ?>

I did not have the if statement. I have it now. I do not get an error message anymore - which I got before - but it does not return anything…

I entered this in blueprint files:

newsimage:
label: News Image
type: image

and in the panel I just selected an image…
hmmm

Are the subpages visible?

If you mean this in the blueprint:

pages: true

I have set it to true as it was on false before. But it does not change anything on the news page…

No, you are filtering pages by visibility:

$page->children()->visible()->flip()

but are your pages visible, i.e. do they have a prepended number in the filesystem? If in doubt, remove visible() and check if the images appear.

https://getkirby.com/docs/content/adding-content/#visible-and-invisible-pages

Ow, yes ther are visible!
And I also do manage to retrieve the titel from $newsarticle, so…

Just realised that there is an echo statement missing, code should be:

<?= $image->url();  ?>

Yes! Got it!
So the eventual code is:

<?php foreach($page->children()->visible()->flip() as $newsarticle): ?>
  	<?php if($image = $newsarticle->newsimage()->toFile()): ?>
  	  <div class="news-image">
  	  	<img src="<?php echo $image->url() ?>" alt="<?php echo $newsarticle->title()->html() ?>">
  	  </div>
  	<?php endif ?>
<?php endforeach ?>

Thanks so much Texnixe!