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:
Horror
Romance
Sci-Fi
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>';
}
}
endwhile;
endif;
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')) {
the_row();
$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
ksort($books);
// loop through books
foreach ($books as $category => $list) {
echo '<h2>',$category,'</h2'><ul>';
// sort the list
sort($list);
foreach ($list as $book) {
echo '<li>',$book,'</li>';
}
echo '</ul>';
}
The topic ‘Sorting a list using repeater and multi-select field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.