Sorting your data with perch_content_custom

When you use perch_content_custom, perch_collection or any of the App custom functions you can use the options array to tell Perch the order you want the data returned in.

In my example introducing this series I showed a template which allows data about sites to be leased to be entered as Perch Content. In that template we have:

These are represented by template IDs:

To order your data you need to pass in two options as described in the documentation, ‘sort’ which is the ID of the data you want to use to sort the content, and ‘sort-order’ which should be one of the following values:

You can also pass in a third option ‘sort-type’. This can be either:

The default is alpha, so you only need to pass this in if you are dealing with something that is always a number so we can treat it as one when the data is sorted.

Sorting in practice

If I want to display my apartments alphabetically by name (A to Z)

<?php perch_content_custom('Intro', array(
  'page' => '/apartments',
  'sort' => 'apartmentname',
  'sort-order' => 'ASC',
  'template' => 'apartment.html'
)); ?>

If I want to reverse that and show them Z to A, I just change the sort-order.

<?php perch_content_custom('Intro', array(
  'page' => '/apartments',
  'sort' => 'apartmentname',
  'sort-order' => 'DESC',
  'template' => 'apartment.html'
)); ?>

To show them with the smallest number of rooms first – and here I am adding the sort-type option set to numeric.

<?php perch_content_custom('Intro', array(
  'page' => '/apartments',
  'sort' => 'rooms',
  'sort-order' => 'ASC',
  'sort-type' => 'numeric',
  'template' => 'apartment.html'
)); ?>

Here they are displayed with the largest number of rooms first.

<?php perch_content_custom('Intro', array(
  'page' => '/apartments',
  'sort' => 'rooms',
  'sort-order' => 'DESC',
  'sort-type' => 'numeric',
  'template' => 'apartment.html'
)); ?>

So you can now sort your data with Perch. We’ll be adding more posts to this series to help you make the most of the custom functions in Perch.