Home › Forums › General Issues › [WP_Query > orderby] Merge date and time fields
Hello everyone,
I created two fields: DATE
and TIME
(for a third-party plugin, I don’t use the DATETIME
field).
I want to use wp_query
to display the posts in order of date (and time).
The problem is that I cannot merge these 2 data, this is either one or the other :
I tried to put an array but it also doesn’t work:
'orderby' => array('event_date' => 'ASC', 'event_time' => 'ASC')
Do you know if this is possible?
If this is not possible, when saving a post, will I be able to copy my 2 fields into a DATETIME
field?
Thanks for your help!
To do this you need to use meta_query and orderby with clauses. See 9th code example for orderby in the WP_Qeury doc https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters
You mean rather the 10th?
‘orderby’ with multiple ‘meta_key’s?
I could have miscounted 😛
It looks like this
$q = new WP_Query( array(
'meta_query' => array(
'relation' => 'AND',
'state_clause' => array(
'key' => 'state',
'value' => 'Wisconsin',
),
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'city_clause' => 'ASC',
'state_clause' => 'DESC',
),
) );
I’m not sure the code does what I want.
I would like my events to be displayed in order of date and time, but knowing that I have my 2 fields which are separate. So my timestamp is distorted.
Date fields store dates in the db in the form of “YYYYMMDD’ so you need to use “CHAR” or “NUMBER” as the field click.
I am not sure how time fields store values, you should check the DB to be sure.
But if you have the right data format then sorting by the two fields should work.
The time is stored in H:i:s
format (for example: 16:30:00).
Unfortunately this doesn’t work:
$q = new WP_Query( array(
'orderby' => array(
'event_date' => 'ASC',
'event_time' => 'ASC',
),
) );
The dates are mixed (and the times too).
I had not seen the little subtlety!
It works! Thank you very much!
I put the code for people who would have the same problem:
'meta_query' => array(
'relation' => 'AND',
'date_clause' => array(
'key' => 'event_date',
'compare' => '=',
),
'time_clause' => array(
'key' => 'event_time',
'compare' => '=',
),
),
'orderby' => array(
'date_clause' => 'ASC',
'time_clause' => 'ASC',
),
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.