• Resolved GusGF

    (@gusgf)


    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??

Viewing 3 replies - 1 through 3 (of 3 total)
  • My reading of this line in the documentation for WP_Query implies to me that to use meta_value_date you need to set the meta_type argument to DATE:

    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 using DATETIME as '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 5 years, 4 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', 
    
    
    Thread Starter GusGF

    (@gusgf)

    Yes Jacob that does indeed seem to work ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘meta_value_date & sorting not working’ is closed to new replies.