Jump to content
fruid

output last image on 2 levels deeper subpage

Recommended Posts

I have an array of pages and each page has 6 subpages.
How do I select a specific field of one of the subpages?
I'm trying to output the image of the last subpage on the top parent page.
So far the only thing that works is to output the image of the first subpage with…

$years = $page->children;

foreach ($years as $year) {
	echo '<img src="' . $year->child->cover->url . '"/>' //cover is the single-item image field
}

the subpages are always titled (an listed) as 06 05 04 03 02 01 
But I want to output the last child which would be 01.
Should I first sort it by title and store in another array? I tried that to no success.

How to use a selector? Something like this?

$years = $page->children;

foreach ($years as $year) {
	echo '<img src="' . $year->child('title=01')->cover->url . '"/>' //cover is the single-item image field
}

Doesn't work. What am I not getting?

thanks for help

Share this post


Link to post
Share on other sites

You can get the last item in a WireArray (a PageArray is a type of a WireArray, i.e. your subpages) using the method last().

https://processwire.com/api/ref/wire-array/last/

An example using last()

// get some parent page
// OR if this page: $page->children;
$parent = $pages->get("id=1234");
$children = $parent->children;

foreach($children as $child) {
    if($child->id === $children->last()->id){
       // this is the last child
	   // e.g, echo its title field
		echo $child->title;
    }
}

This is just one way to do it. Depending on your use case, you could also use a counter in the loop. Note though that if your 01 child is moved, it will obviously no longer be the last child :-).

 

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...