WP_Query using meta_query with relation OR and orderby meta_value doesn’t work

The issue is that WordPress are getting all posts that has a ‘startDate’ meta key, no matter the meta value.

You can understand that form this part of the request:

...
AND (
 wp_postmeta.meta_key = 'startDate'
 OR ( mt1.meta_key = 'startDate' AND CAST(mt1.meta_value AS CHAR) >= '20140305' )
 OR ( mt2.meta_key = 'endDate' AND CAST(mt2.meta_value AS CHAR) >= '20140305' )
)
...

so if a post has a the meta_key ‘startDate’ it will be returned.

The culprit of this behavior is the 'meta_key' argument

...
new WP_Query( array(
    'post_type'     => 'evenements',
    'orderby'       => 'meta_value',
    'meta_key'      => 'startDate', // <-- this is the culprit
    ...

However, if you remove it you will not be able to order by a meta value, because, sometimes WordPress is… (I don’t know the english term, complete the sentence by yourself).

The solution is (should be) put the first part of your meta query (regarding start date), as plain arguments (not part of meta_query), and the second part (regarding end date) inside meta_query array:

$evenements = new WP_Query(array(
  'post_type'      => 'evenements',
  'meta_key'       => 'startDate',
  'meta_value'     => date('Ymd'),
  'meta_type'      => 'NUMERIC',
  'meta_compare'   => '>=',
  'orderby'        => 'meta_value',
  'order'          => 'ASC',
  'meta_query'     => array(
    'relation'  => 'OR',
     array (
       'key'     => 'endDate',
       'value'   => date('Ymd'),
       'compare' => '>=',
       'type'    => 'NUMERIC'
     )
  )
));

Your setup is too complex to make me test it accurately, so try it yourself and let me know.

Leave a Comment