Accessing 'Single Project' image field while looping on 'All Project' page


I’m trying to access the complete url of 1 image selected in the image field .
Example of a single project with its image field:

And my loop code is below:


$projects = page('projects')->children()->visible();
if(isset($limit)) $projects = $projects->limit($limit);


<div id="all_projects">

    <?php $i = 0; foreach($projects as $project): ?>
    	<a href="<?= $project->url() ?>" class="single_project<?= $i++ ?>">
			<h3 class="showcase-title"><span><?= $project->title()->html() ?></span> </h3>
            <img src="<?= $project->main_thumbnail() ?>" class="showcase-image" />
    <?php endforeach ?>


I’m currently only able to get the file name only or an incomplete url . As demonstated below:
Complete url im trying to get :
What im able to get:
<?= $project->main_thumbnail() ?> gets me just ‘amt_pcf_2.jpg

<?= $project->main_thumbnail()->url() ?> gets me ‘http://localhost:8888/sitename/amt_pcf_2.jpg

Any help is appreciated


The field is storing the file name as a string. You need to pick the string up and turn it into a file object via toFile() or image()

<?= $project->main_thumbnail()->toFile()->url() ?>;

Better still, it’s good practice to check the image physically exists first, since its possible for the file itself to be deleted but the reference to it can remain in your field. Errors will be thrown if you try to work with an image that does not exist…

<?php if($projectimg = $project->image($project->main_thumbnail())): ?>
  <img src="<?= $projectimg->url() ?>" alt="<?= $projectimg->alt() ?>">
<?php endif ?>


works nicely! thanks!


No problem.

On a side note, I would suggest not using $1 to add classes to the project, it’s not safe. If you change the sorting for example, the class number will potentially end up on another project, which will apply the CSS rule to the wrong project.

You could use the UID instead which is safer but can change if you update the page title:

class="<?= $project->uid() ?>"

If you really want to add a fixed unique class to the project that will never change, I would suggest the AutoID plugin. You need to save all the pages after installing it to generate the unique ID numbers.

class="project-<?= $project->autoid() ?>"


noted. i’m only using it to style the grid layout im doing. not really as an identifier for which project it is.


In that case, you don’t need the classes at all. You can do that with css using nth().


well i simplified the loop in my code above. in reality its a little complicated then that. there’s some other dom elements in between each projects haha. and using nth for those situations is not ideal.