Reverse the Order of Repeaters Content

Repeaters Tags allow you to easily add a variable number of items (each containing custom fields of your choosing) to a template.

By default the items inside a repeater are displayed in the same order in which they are saved. There are cases where it is useful to display the items in reverse (e.g. software changelog, actor filmography) . At the time of writing (as of Perch 3.1.2) there is no way of doing this from within the template, but you can acheive this with PHP.

Let’s say you have a repeater:

<perch:repeater id="list" label="My List">
    <perch:before><ul></perch:before>
        <li><perch:content id="title" type="text" label="Title"></li>
    <perch:after></ul></perch:after>
</perch:repeater>

If you’re using a content region, you have to use perch_content_custom() to be able to reverse it:

perch_content('Region', true);

perch_content_custom('Region', [
    'each' => function($item) {
        $item['list'] = array_reverse($item['list']);
        return $item;
    }
]);

list in $item['list'] refers to the field’s ID. We use <perch:repeater id="list"> so our ID is list.

You can do the same with other function such as perch_collection():

perch_collection('Articles', [
    'each' => function($item) {
        $item['repeater_id'] = array_reverse($item['repeater_id']);
        return $item;
    }
]);

Doing it safely

It is better to check whether the array $item actually has the field we’re looking for:

perch_collection('Articles', [
    'each' => function($item) {
        if (isset($item['repeater_id'])) {
            $item['repeater_id'] = array_reverse($item['repeater_id']);
        }
        return $item;
    }
]);
link