Home › Forums › General Issues › Sorting by 2 acf fields, date and time problem
Hi,
Any idea why my wp_query doesn’t work like it should ?
It should order posts by date and time. For now it works only for dates. Instead of “start_at” it orders by post creation time.
<?php // Meta query for tab
$current_date = date('Ymd');
$future_date = date('Ymd', strtotime('+6 days'));
$args = [
'post_type' => 'events',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_query' => [
[
'key' => 'event_date',
'value' => [$current_date, $future_date], // Use an array to specify a range
'compare' => 'BETWEEN', // Use BETWEEN to specify a range
'type' => 'DATE'
],
[
'key' => 'start_at',
'compare' => 'EXISTS' // Include this line to ensure 'start_at' meta field exists
]
],
'orderby' => [
'event_date' => 'ASC', // Order by 'event_date' in ascending order
'start_at' => 'ASC', // Then order by 'start_at' in ascending order
'meta_type' => 'TIME' // Specify meta_type as 'TIME' to correctly order by time format
]
];
include(locate_template('template-parts/tabs-inner-include.php', false, false));
?>
Ok I sorted it out myself. You need to use named meta query.
<?php // Meta query for tab
$current_date = date('Ymd');
$future_date = date('Ymd', strtotime('+6 days'));
$args = [
'post_type' => 'events',
'post_status' => 'publish',
'posts_per_page' => 12,
'meta_query' => array(
'relation' => 'AND',
'date_meta' => array(
'key' => 'event_date',
'value' => [$current_date, $future_date], // Use an array to specify a range
'compare' => 'BETWEEN', // Use BETWEEN to specify a range
'type' => 'DATE',
),
'time_meta' => array(
'key' => 'start_at', // 'start_at' is the custom field storing the time value
'type' => 'TIME' // Use 'TIME' meta type for 'start_at' field
),
),
'orderby' => [
'date_meta' => 'ASC', // Order by 'event_date' in ascending order
'time_meta' => 'ASC' // Then order by 'start_at' in ascending order
]
];
include(locate_template('template-parts/tabs-inner-include.php', false, false));
?>
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.