If you have a collection of posts that need sorted or filtered by a repeater field, this can be a bit of a pain to query for. The normal WP_Query meta_query arguments won’t work here.

To visualize this, lets imagine you have a custom post type of Trips. Inside Trips, you have repeating fields for Dates of each trip and a checkbox if it should be Featured.

If you want to show ALL Trips that are marked as Featured and sorted by the Date of each trip, you’ll need to build an array with all your post_meta then output them via a loop.

Here’s what we need to do:

  • Create an empty array to hold our post data
  • Create a new WP_Query with any arguments we require
  • Start the loop
  • Loop through the repeater fields
  • Optional: I added an if statement to filter by Featured only
  • Add our post data to our array using key => value format
  • Sort out data by date
  • Output via foreach loop

A word on sorting in PHP

There are several built-in functions to sort, the best resource for quickly knowing which sort function to use is this chart:

Props TutsPlus (https://code.tutsplus.com/tutorials/working-with-php-arrays-in-the-right-way–cms-28606)

Some helpful links to further reading about sorting options in PHP:

The full code below shows an example of a basic custom sort, which we can pass to usort if none of the pre-defined PHP sorting functions fit the bill.

You could achieve the same results with asort in this case, replacing both usort() and subval_sort function with just asort( $post_data );

Here’s the full code: