Home › Forums › Add-ons › Repeater Field › Sort Repeater Field by Reverse Date Entered
Hi,
So the normal sort on repeater field is oldest entered goes to top – I want the reverse of this last repeater field entered goes to top.
I have my repeater code with array_multisort
function trs_testimonial_loop_sort() {
//My ACF Fields for reference
//testimonials - field group
//testimonial - sub-field
//testimonial_header - sub-field
$repeater = get_field('testimonials');
/*
* Obtain a list of columns
* - $column_id will look something like this:
Array
(
[0] => 3
[1] => 2
[2] => 4
[3] => 1
)
*/
foreach( $repeater as $key => $row ) {
$column_id[ $key ] = $row['testimonial_header'];
}
/*
* Use the $column_id array to sort the $repeater array
*/
array_multisort( $column_id, SORT_DEC, $repeater );
/*
* Do stuff with the repeater... Note: has_sub_field loop will not use the "sorted" $repeater array
*/
foreach( $repeater as $row ) {
$testimonial_p = $row['testimonial'];
$testimonial_h2 = $row['testimonial_header'];
echo '<article><div class="entry-content testimonial">';
echo '<p>' . $testimonial_p . '</p>';
echo '<h2>' . $testimonial_h2 . '</h2>';
echo '</div></article>';
}
}
So really the sort here sorts alpha according to the text strings, how would I do this sort by the date and order the repeater field was created.
hi, try if this works: (sort by date-field instead of header)
foreach( $repeater as $key => $row ) {
$thedate = $row['your_date_field'];
$column_id[ $key ] = strtotime($thedate);
}
array_multisort( $column_id, SORT_DESC, $repeater );
foreach( $repeater as $row ){
i assume date field is part of the repeater.
replace your_date_field with name of the date field. (part of my code)
Hi again,
Thanks for your help – actually I didn’t have a date field – but added one and used this
foreach( $repeater as $key => $row ) {
$column_id[ $key ] = $row['date_added'];
}
/*
* Use the $column_id array to sort the $repeater array
*/
array_multisort( $column_id, SORT_DESC, $repeater );
The topic ‘Sort Repeater Field by Reverse Date Entered’ 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.