WordPress meta_query and order by custom field

I discovered the problem by inspecting the actual SQL created by WP_Query. I realized that the generated SQL query has 2 INNER JOINs, one for the meta_key and another for the actual meta_query.

Basically on one hand it is filtering those films that have a showings_%_start_datetime in the next seven days, and on the other hand (independently) it is ordering the films by their showings_%_start_datetime value.

Just moving the meta_query parameters to the base query works fine:

query = new \WP_Query( array(
    'numberposts'   => -1,
    'post_type'     => 'film',
    'meta_key'      => 'showings_%_start_datetime',
    'meta_value'    => array( time(), strtotime( '+7 days' ) ),
    'meta_type'     => 'NUMERIC',
    'meta_compare'  => 'BETWEEN',
    'orderby'       => 'meta_value_num',
    'order'         => 'ASC',
));

Leave a Comment