meta_value_date & sorting not working
-
I’m fetching a custom post type called ‘event’ and am using a plugin called ACF to add a custom field (of type ‘date picker’) within the WP editor for this post type. Using the query below I’m fetching ‘events’ and ordering them or trying to at least.
$eventQuery = new WP_Query(array('post_type'=>'event', 'posts_per_page'=>-1, 'order'=>'asc', 'orderby'=>'meta_value_date', 'meta_key'=>'event_date'));The problem is the ‘events’ are not being sorted correctly unless I change the type from ‘meta_value_date’ to ‘meta_value_num’ for the sort. According to the documentation ‘date picker’ in ACF stores dates in the DB as ‘YYYYMMDD’ so one can see why ‘meta_value_num’ works but why does ‘meta_value_date’ equally not work as a WP query??
-
My reading of this line in the documentation for
WP_Queryimplies to me that to usemeta_value_dateyou need to set themeta_typeargument toDATE:You may also specify
'meta_type'if you want to cast the meta value as a specific type. … When using'meta_type'you can also use'meta_value_*'accordingly. For example, when usingDATETIMEas'meta_type'you can use'meta_value_datetime'to define order structure.Which would look like this:
$eventQuery = new WP_Query( array( 'post_type' => 'event', 'posts_per_page' => -1, 'order' => 'ASC', 'meta_key' => 'event_date' 'meta_type' => 'DATE', 'orderby' => 'meta_value_date', ) );However I can’t imagine this being faster than just sorting numerically, if dates are stored as YYYYMMDD, so my suggestion would be to stick with
meta_value_num.-
This reply was modified 6 years, 11 months ago by
Jacob Peattie.
please used this args in your WP_Query meta_key args used the acf field name and orderby args used the meta_value
'orderby'=>'meta_value', 'meta_key'=>'event_date', 'order'=>'DESC',Yes Jacob that does indeed seem to work 🙂
-
This reply was modified 6 years, 11 months ago by
The topic ‘meta_value_date & sorting not working’ is closed to new replies.