Jump to content

How to output images in descending order?


SwimToWin
 Share

Recommended Posts

How might I programmatically output images from an Image field from another template in descending order?

  • I want to reverse the order of images on the front-end page (see code below).
  • I want to keep the order in ProcessWire Admin.
  • The Image field accepts multiple images.

Code:

foreach ($page->children() as $p) {
	if( isset($p->foo->id) && $pages->get($p->foo->id)->images->count>0 ) {
		foreach ($pages->get($p->foo->id)->images as $img) {
			echo "<img data-src=\"{$img->width(140)->url}\" width=\"\" height=\"\" alt=\"{$p->foo->title}\" class=\"uk-align-right uk-visible@m\" uk-img>";
		}
	}
}

Things I tried (that didn't have an effect):

$pages->get($p->foo->id)->images->sort("sort=-sort")
$pages->get("id={$p->foo->id},sort=-sort")->images

I also wanted to try a for() loop but didn't know how to..   

# Failed attempts:
$pages->get($p->foo->id)->images[0];
$pages->get($p->foo->id)->images->1;

# This works - but only for first and last (not a third image) and I would need to check if each image existed.
$pages->get($p->foo->id)->images->first;
$pages->get($p->foo->id)->images->last;

I am aware that ProcessWire isn't specifically designed for working with child pages this way - it's probably even a bad practice - it's just that it almost always works very, very well. ?

PS: Would you normally set the width and height attributes, or leave them out?

Link to comment
Share on other sites

What is an "external template"? You mean a regular frontend template?

I'm not quite sure what you're asking: Reverse all child pages only? Or keep the page order as in the admin, but reverse the images per page only? If the latter, you could do something like:

$imgs = $page->images;

if ($imgs) {
    $gmi = array();
    foreach ($imgs as $img) {
        array_push($gmi, array($img->url, $img->description, $img->title));
    }
    $images = array_reverse($gmi);
    foreach ($images as $img) {
        $content .= "<h2>{$img[2]}</h2><img src='{$img[0]}' alt='{$img[1]}'>";
    }
}

Basically just array_reverse()

  • Thanks 1
Link to comment
Share on other sites

@dragan - That'll work. Thanks!

I use the snippet below that copies the full Image object so that all Image properties remain intact for use in the subsequent foreach():

foreach ($page->children() as $p) {
	$imgs = $pages->get($p->foo->id)->images;
	if( isset($p->foo->id) && $imgs ) {
		$gmi = [];
		foreach ($imgs as $img) {
			$gmi[] = $img;
		}

		foreach ( array_reverse($gmi) as $v) {
			echo "<img src=\"{$v->width(140)->url}\" alt=\"{$p->foo->title}\">";
		}
	}
}

 

Link to comment
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
 Share

×
×
  • Create New...