0

How to apply 'order_by' in WordPress query in the following example:

I have a query to get all posts with custom field for event dates greater or equal current date. I can have up to 10 event dates (event_date_0, event_date_1 etc) per post so I run a loop in meta query like:

$meta_query_array = array(
    'relation' => 'OR'
); 

for($date_row = 0;$date_row < 10; $date_row++){
    $single_date_query = array(
        'key'       => 'event_date_'.$date_row,
        'value'     => date('Y-m-d'),
        'compare'   => '>=',
        'type'      => 'DATE'
    );
    array_push($meta_query_array, $single_date_query);
}

$args = array(
    'post_type'         => array('events'),
    'posts_per_page'    => -1,
    'meta_query'        => $meta_query_array
);

$events = new WP_Query( $args )

That part works fine. I get all posts where at least 1 of 10 event dates is greater or equal current date.

Now I need to apply sorting (order by). I'd like to set order_by by another custom field "rating" DESC. And this is where I fail.

Simply added to $args, like:

$args = array(
    'post_type'         => array('events'),
    'posts_per_page'    => -1,
    'meta_query'        => $meta_query_array,
    'meta_key'          => 'rating',
    'orderby'           => 'meta_value_num',
    'order'             => 'DESC',
);

is not working. Not sure how to push it to meta query, if need be.

Any advice would be much appreciated.

3

As of WordPress 4.2, you can combine meta_query and orderby. The following example is taken from make.wordpress.org.

Example of a simple meta_query:

$q = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'AND',
        'state_clause' => array(
            'key' => 'state',
            'value' => 'Wisconsin',
        ),
        'city_clause' => array(
            'key' => 'city',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => 'city_clause',
);

The orderby parameter just includes the key of your meta_query. You could also set it to state_clause for a different ordering.

What's really cool is the possibility to combine different order clauses by passing an array to orderby:

'orderby' => array(
    'city_clause' => 'ASC',
    'state_clause' => 'DESC',
),

This would translate to a SQL query like

ORDER BY city_clause ASC, state_clause DESC

for more complex ordering types.

  • It all would work great if only I could have 'relation' => 'AND' - however, in my case I need to have 'OR' - So in SQL it would look sth. like: "SELECT * FROM events WHERE event_date_0 >= CURDATE() OR event_date_1 >= CURDATE() OR ... event_date_9 >= CURDATE() ORDER BY rating DESC – dkatwp Feb 24 '16 at 10:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.