Home › Forums › General Issues › Sort posts in a widget using 2 ACFs
I have a field group for standard WP posts that includes among others) the following optional ACFs:
To be clear: not all the posts that have start_date value also have a start_time value.
I have custom widget that only displays posts that have a start_date value that’s (1) today or later, and (2) that’s within the next N days, where N is set in the widget admin interface. The posts are sorted by start_date in ascending order.
That part all works just fine. Where I’m having trouble is being able to include the optional start_time ACF in the sort order so that posts would be listed like this:
February 23
February 24 10:00am
February 26
March 5 8:00am
March 5 10:00am
March 6
This is the $args array that sorts (correctly) only by start_date:
$args = array(
'ignore_sticky_posts'=> 0,
'post_type' => 'post',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'start_date', // ACF field for event start date
'value' => date('Ymd', strtotime("+{$nr_days_ahead} days")), // restrict start date to no more than today + $nr_days_ahead
'compare' => '<=',
'type' => 'DATE'
),
array(
'key' => 'start_date', // ACF field for event start date
'value' => $today,
'compare' => '>=',
'type' => 'DATE'
)
),
'posts_per_page' => $nr_posts,
'cat' => $categories,
'meta_key' => 'start_date',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
I spent quite a bit of time today with ChatGPT (just in case anyone feels like suggesting that approach), but never got anywhere (other than a couple critical errors that brought the site down, but I can manage that all by myself).
Any suggestions?
Some issues with your current code.
ACF does not store date fields in the DB as dates. It saves strings that are in the format of ‘Ymd’, so using a type of “DATE” will produce errors.
If you want to sort by the second field then that field must have a value in the DB (even if that value is an empty string). WP will ignore any posts that do not have a value set for a field. I’m not sure what you mean by optional, but in this case the field would always need to be visible and allow no input.
You must be logged in to reply to this topic.
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.