Home › Forums › General Issues › Sort post by time picker field doesn't work
Hello,
I want to sort the results from a wp_query with a custom field, but this doesn’t work.
Code:
$args = array(
'post_type'=> 'myposttype',
'order' => 'DESC',
'meta_key' => 'my_date_time',
'orderby' => 'meta_value_num',
'posts_per_page' => get_field('sf_perpage', 'option'),
'paged' => $paged
);
query_posts( $args );
The date/time field stores values in standard MySQL date formation. Datatype should be set to either string or date
'orderby' => 'meta_value',
'meta_type' => 'CHAR'
Still doesn’t work.
Output:
1. 16.04.2018
2. 21.02.2018
3. 20.04.2018
4. 19.01.2018
Should be:
1. 20.04.2018
2. 16.04.2018
3. 21.02.2018
4. 19.01.2018
You can try setting meta_type
to DATETIME
https://codex.wordpress.org/Class_Reference/WP_Query
I don’t see anything else in this query that would cause the problem.
Also doesn’t work could the problem be because i set a custom return value in the field (look at the attached image)
No, queries are done based on the value in that database. A date time field is stored in standard sql date/time format "Y-m-d H:i:s"
If you have everything in your query correct then the something is interfering with the query. I would start here and figure out if the correct query is being run https://ben.lobaugh.net/blog/45390/wordpress-how-to-view-the-sql-query-generated-by-wp_query
That’s the query:
SELECT SQL_CALC_FOUND_ROWS wp_gqw8d5_posts.ID FROM wp_gqw8d5_posts INNER JOIN wp_gqw8d5_postmeta ON ( wp_gqw8d5_posts.ID = wp_gqw8d5_postmeta.post_id ) WHERE 1=1 AND ( wp_gqw8d5_postmeta.meta_key = ‘my_date_time’ ) AND wp_gqw8d5_posts.post_type = ‘myposttype’ AND (wp_gqw8d5_posts.post_status = ‘publish’ OR wp_gqw8d5_posts.post_status = ‘acf-disabled’ OR wp_gqw8d5_posts.post_status = ‘private’) GROUP BY wp_gqw8d5_posts.ID ORDER BY wp_gqw8d5_postmeta.meta_value+0 DESC LIMIT 0, 10
The +0 at the end of this
ORDER BY wp_gqw8d5_postmeta.meta_value+0
not sure what it means but at a guess I’d say it has to do with still treating the value as a number. Check your arguments again. https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
The topic ‘Sort post by time picker field doesn't work’ 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.