Home Forums ACF PRO Sorting a list using repeater and multi-select field


Sorting a list using repeater and multi-select field

  • I’m using a repeater field containing a multi-select and a title field. On the front-end I’m trying to organize the content the user enters like so:


    • Title 1
    • Title 2


    • Title 2
    • Title 4


    • Title 3
    • Title 4
    • Title 5

    So the titles should show up in multiple lists if multiple categories were selected. This is what I have so far:

    if ( have_rows('books') ):
        while (have_rows('books') ) : the_row();
        $cat = get_sub_field_object('category');
        $choices = $cat['choices'];
        $values = $cat['value'];
        $title = get_sub_field('title');
        foreach ( $choices as $key => $choice ) {
            if (in_array($key, $values)) {
                echo '<li class="' . $key . '">' . $title . '</li>';

    It correctly outputs the titles multiple times (depending on how many categories were added), but how do I sort them so that it shows organized lists as described above?

  • Not sure I understand your setup entirely and just want to make sure I have it correct.

    You have a repeater. Each row of the repeater has a “Book Title” and a “Book Category” where the category is something like horror, romance, sci-fi, etc.

  • Hey John, that’s correct! The book title is a text field, and the book category is a multi select field.

  • Just wanted to make sure, didn’t want to answer the wrong question. This may not be the best way to do this but it’s the way I’d do it because it is the most straight forward. What you need to do is put the values from the repeater into and array that can be sorted.

    $books = array();
    if (have_rows('books')) {
      while (have_rows('books')) {
        $category = get_sub_field('category');
        if (!isset($books[$category])) {
          $books[$category] = array();
        $books[$category][] = get_sub_field('title');
    // sort the categories
    // ksort sorts the array by the element index
    // loop through books
    foreach ($books as $category => $list) {
      echo '<h2>',$category,'</h2'><ul>';
      // sort the list
      foreach ($list as $book) {
        echo '<li>',$book,'</li>';
      echo '</ul>';
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Sorting a list using repeater and multi-select field’ is closed to new replies.