Function called only once in foreach

I’ve been bashing my head at this problem.
I’ve created a simple function in a plugin file which is working great:

function getresponsiveimage($portfolioimg, $page) {
	$img = $page->image($portfolioimg);
	echo '<img class="b-lazy" sizes="(max-width: 1200px) 100vw, 1200px" width="1200" height="800" data-src="';
	echo $img->url();
	echo '" srcset="';
	echo thumb($img, array('width' => 300))->url();
	echo ' 300w,';
	echo thumb($img, array('width' => 768))->url();
	echo ' 768w,';
	echo thumb($img, array('width' => 1024))->url();
	echo ' 1024w" alt="';
	if ($img->caption()->isNotEmpty()) {
		echo $img->caption()->html();
	} else {
		echo $page->title()->html();
	echo '">';

I can call the image easily for just one image but if I call it within a foreach loop, it simply returns the first item of the loop and stops. I’m pretty sure this is a problem with my code but I can’t put the finger on what’s wrong…

Here’s my foreach loop:

<?php foreach ($page->portfolioimages()->toStructure() as $portfolioimage) {
    getresponsiveimage($portfolioimage->toFile(), $page);

Which outputs the first image and then stops, no errors (debug is on and console is logging).

Strange that you get no error message and everything else gets rendered and the first image gets rendered as well.

In your function, you expect a string, but you pass an image object. If you remove toFile() it should work.

<?php foreach ($page->portfolioimages()->toStructure() as $portfolioimage) {
    getresponsiveimage($portfolioimage, $page);

I tried that before but then I get an error:
Call to a member function url() on a non-object
Referring to line 5 of the plugin:
echo $img->url();

I do get the first image when using toFile()

Do all the images exist that you loop through?

As far as I know, $page->image() takes a filename as parameter (or no parameter), not an image object;

What is the structure field called? You are calling toFile() on the structure item, not on a field.

So if the filename is stored in a name field in your structure, use this:

<?php foreach ($page->portfolioimages()->toStructure() as $portfolioimage): ?>
    <?php getresponsiveimage($portfolioimage->name(), $page) ?>
<?php endif ?>

What would also help: Do you get any HTML output after your images? For example your footer snippet.

You opened my eyes to a very stupid mistake…
I was treating a list of files (from the selector plugin) as a structure field…

Change to:

And it’s now working as expected. Thanks both for your quick help !

1 Like