2 Problems - Image Field and Filter Tag

Hi,

I’m stuck on two problems.
The first one is simple, I would like to show the CoverImage from a Article on the HomePage.

On my Article page: (Child) (work fine)

<?php $coverimage = $page->coverImage()->toFile(); ?>
<img src="<?= $coverimage->url() ?>">

On my HomePage (Parent) (doesn’t work)

<?php foreach($page->children()->visible()->paginate(8) as $article): ?>
	<?php $coverimage = $article->coverImage()->toFile(); ?>

	<a href="<?= $article->url() ?>">
		<img src="<?= $coverimage->url() ?>" alt="">
	</a>
<?php endforeach ?>



Second problem.
I would like to show related article filter by the first tag of Article tags field for exemple article with the ‘Cheese’ tag :


So in my Article blueprint I had a tags field :

<?php foreach($parent->children()->visible()->limit(9)->filterBy('tags', 'tag->first()', ',')) as $article): ?>

blahblah

<?php endforeach ?>

Thank you with :heart:

For your first issue, I suspect one of your articles does not have a CoverImage set. You need to check the image exists before trying to use it. Something like this in you loop…

<?php
<?php foreach($page->children()->visible()->paginate(8) as $article): ?>
// let's assume the filename is stored in a field called coverImage
$image = $article->image($coverImage());

// always check if the image exists!
if($image):
?>
  <img src="<?= $image->url() ?>" alt="">
<?php endif ?>
<?php endforeach ?>

AS for the second issue, theres probably something on this page that will help you.

1 Like

You can shorten this a. bit:

<?php
<?php foreach($page->children()->visible()->paginate(8) as $article): ?>

// always check if the image exists!
if($image =  $article->coverImage()->toFile()):
?>
  <img src="<?= $image->url() ?>" alt="">
<?php endif ?>
<?php endforeach ?>

To. get the first tag:

$firstTag = '';
$tags = $page->tags()->split(',');
if(isset($tags[0])) {
  $firstTag = $tags[0];
}

dump($firstTag);
1 Like

Thank both of you, the coverImage is working and first tag too but there is a another problem with it.

The related articles snippet filter by the first tag show only 2 or 3 articles whereas I have 10 articles with the tag. I’ve try to figure out why all the this afternoom but I don’t find why.

->filterBy('tags', $firsttag, ' , ')

Well, you limit your collection to 9 articles first, then filter. That means that while there are probably more articles, they won’t be fetched if they are not within the first 9. You probably want to filter. first, then limit, if you want to limit at all.

<?php
$relatedArticles = $parent->children()->visible()->filterBy('tags', $firsttag,  ',')->limit(9) ;
foreach($relatedArticles as $article): ?>

Thank you very much ! How can I be so stupid for something so simple.

Thanks ! :heavy_heart_exclamation: