I have a custom query and I am filtering out events by custom field: event-month. I simple filter our the events that dont have a month_number = to date(“n”);

Its a pretty great little query, but I need to orderby another custom field, event_date.

Do I need a custom function or something to get this done. I simply want to orderby => event_date

but I am currently using event-month for my query.

<?php 
        $event_query = new WP_Query(
        array( 
          'post_type'   => 'event',        // only query events
          'meta_key'    => 'event-month',  // load up the event_date meta
          'order_by'    => '',
          'order'       => 'asc',         // ascending, so earlier events first
          'meta_query'  => array(
             array(         // restrict posts based on meta values
              'key'     => 'event-month',  // which meta to query
              'value'   => date("n"),  // value for comparison
              'compare' => '=',          // method of comparison
              'type'    => 'NUMERIC'         // datatype, we don't want to compare the string values
            ) // meta_query is an array of query ites
           ) // end meta_query array
          ) // end array
        ); // close WP_Query constructor call

?>

3 Answers
3

Despite meta_key being deprecated, it is still required to get the orderby to work correctly.

First and foremost though, there’s an error with your code, and that’s in using order_by and not orderby (there’s no underscore in the orderby arg).

Give this a shot and see how it works out for you.

$event_query = new WP_Query( array( 
    'post_type'   => 'event',
    'meta_key'    => 'event-month',
    'meta_query'  => array(
        array( 
            'key'     => 'event-month',
            'value'   => date("n"),
            'compare' => '=',
            'type'    => 'NUMERIC'
        )
    ),
    'orderby'    => 'meta_value',
    'order'       => 'asc', 
) );

If you want to add a second meta key, and sort by that key, just ensure that key is inside the meta_key arg, eg.

$event_query = new WP_Query( array( 
    'post_type'   => 'event',
    'meta_key'    => 'some-key',
    'meta_query'  => array(
        array( 
            'key'     => 'some-key',
            'value'   => 'whatever',
            'compare' => '=',
            'type'    => 'NUMERIC'
        ),
        array( 
            'key'     => 'event-month',
            'value'   => date("n"),
            'compare' => '=',
            'type'    => 'NUMERIC'
        )
    ),
    'orderby'    => 'meta_value',
    'order'       => 'asc', 
) );

Odd that you should need meta_key for the sort, but i don’t see the orderby being respected without it, i can see how the query appears inside debug bar’s queries tab and as far as i can tell meta_key is currently required to get a proper sort on meta_value.

Leave a Reply

Your email address will not be published. Required fields are marked *