I have a custom field called "departure_dates" which is an array of objects with the keys "start_date" and "end_date".

as Json, it would look like:

  "departure_dates": [
      "start_date": "Dec 11, 2017",
      "end_date": "Dec 11, 2017"
      "start_date": "Dec 21, 2017",
      "end_date": "Dec 29, 2017"

I want to intercept a query for a particular post type and sort the list by start_date.

I tried looking at the following meta_query option but it's not seeming to work

function show_by_date ( $query ) {

 // only modify queries for 'my_cpt' post type

 if ( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'my_cpt' ) {

    //Get original meta query if there is one
    $meta_query = $query->get('meta_query');

            //Add our meta query to the original meta queries
            $meta_query[] = array(
                                'order' => 'DESC',
                                'orderby' => 'meta_value'

             $query->set('orderby', 'meta_value_num'); //probably need this because the value is date

    return $query;

} add_action( 'pre_get_posts', 'show_by_date',  20 );

What am I missing?

  • You can't sort by a value within a serialised array (which is what your meta value would be). You should store each date as a separate meta value. A variation on that would be just storing the date you need to sort by separately. So have departure_dates as a value with all the dates, but also store the first start_date separately just for the purposes of sorting. – Jacob Peattie Dec 6 '17 at 8:58
  • Huh. Is there any good way to create a repeater field that stores some of the values in other meta field that isn't obvious to the user? I hate that I have to do it this way but it is what it is. – friendlyfire Dec 6 '17 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.