Last active
July 24, 2024 18:15
-
-
Save bmoredrew/62411542bc045da7aca41c87d99f6edd to your computer and use it in GitHub Desktop.
Sort Posts by ACF Repeater Field Using Multidimensional Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Create an empty array for storage | |
$post_data = array(); | |
// Set arguments for your query | |
$args = array( | |
'post_type' => 'trips', | |
'posts_per_page' => 999 | |
); | |
// Do our query with any arguments from above | |
$query = new WP_Query( $args ); | |
if ( $query->have_posts() ) | |
{ | |
while ( $query->have_posts() ) | |
{ | |
$query->the_post(); | |
// Setup our repeater | |
if( have_rows('trip_info') ): | |
while ( have_rows('trip_info') ) : the_row(); | |
// Optional - Only get posts that match a true false within our repeater | |
if ( get_sub_field('featured_trip') ) | |
{ | |
// Build our array with the data we need using key => value | |
$post_data[] = array( | |
'title' => get_the_title(), | |
'date' => get_sub_field('trip_date') | |
); | |
} | |
endwhile; | |
endif; | |
} | |
} | |
// Custom function to use in our sort to list the items by date | |
function subval_sort( $a, $b ) | |
{ | |
if ( $a['date'] == $b['date'] ) | |
return 0; | |
return $a['date'] < $b['date'] ? -1 : 1; | |
} | |
// Sort our multidimensional array by sub array value | |
usort( $post_data, 'subval_sort' ); | |
// We can now work our data normally through easy to access methods | |
foreach ( $post_data as $post ) | |
{ | |
echo $post['title'] . ' ' ; | |
echo $post['date']; | |
echo '<br/>'; | |
} |
ntenhoedt
commented
May 7, 2022
via email
Hey, glad it’s of help!
I would not know how to do that, sorry!
… On 2 May 2022, at 19:15, LadyGeekGeek ***@***.***> wrote:
@ladygeekgeek commented on this gist.
Thanks for this I'm using this to sort events (with multiple dates as acf repeater field) by date. Is there any easy way to add the shared event date as a header with all posts sharing same date beneath it? In essence event listings by day?
—
Reply to this email directly, view it on GitHub <https://gist.github.com/62411542bc045da7aca41c87d99f6edd#gistcomment-4151944>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/ACZW3FWUZ3NQHNJ7WMFHCBTVIAES5ANCNFSM4LE4PQZQ>.
You are receiving this because you commented.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment