Custom Snippet - Get the last 50 images uploaded from across all galleries

This question came through modmore support recently, and it may well be useful to others looking to do something similar! :slight_smile:

If you’d like to display the latest images uploaded from across all the galleries you have on your site, here’s one way of doing that using a custom snippet!

Create a new snippet in MODX and add the following code:

<?php

// This part loads MoreGallery
$corePath = $modx->getOption('moregallery.core_path', null, $modx->getOption('core_path') . 'components/moregallery/');
$moreGallery = $modx->getService('moregallery', 'moreGallery', $corePath . 'model/moregallery/');
if (!($moreGallery instanceof moreGallery) || !($moreGallery instanceof \modmore\Alpacka\Alpacka)) {
    $modx->log(modX::LOG_LEVEL_ERROR, 'Error loading moreGallery class from ' . $corePath);
    return 'Error loading moreGallery class.';
}

// Search for the last 50 images with most recent first
$c = $modx->newQuery(mgImage::class);
$c->limit(50);
$c->sortby('uploadedon', 'DESC');
$images = $modx->getCollection(mgImage::class, $c);

$output = '';
foreach ($images as $image) {
    $imageArray = $image->toArray();
    
    // This will simply output the full <img> tag of each image in order. Remove this if you use a chunk (see below)
    echo $imageArray['full_view'];
    
    // Uncomment this to see all the image data available
    //print_r($imageArray);
    
    // Uncomment the next line to use a custom chunk for formatting 
    //$output .= $modx->getChunk('name of your chunk here', $imageArray);
    
}

return $output;

As you can see, there are a few options in the snippet on what to output. As default, it will output each image in an <img> tag. If you’d like to use a chunk with your own formatting, uncomment the line with getChunk().
You’ll need to create a chunk and add placeholders to it.
To see what placeholders are available to the chunk, you can uncomment the print_r($imageArray); line. This will output an array of placeholder keys you can use.

For example, if you wanted your chunk to show the gallery resource id, the date uploaded, and the image URL, you could use:

[[+resource]]
[[+uploadedon:date=`%d %B %Y`]]
[[+file_url]]

Don’t forget you can change the date formatting to your preference!
https://docs.modx.com/3.x/en/building-sites/tag-syntax/date-formats

2 Likes