0

How do I structure a sql that: 2 checks if meta_value is in future or has no meta_value at all and 1 orders by meta_value (meta_key => datum_event), and conditionally if this meta_value is empty uses postdate to order.

The ordering of the query should be handled like one block (not two ordered sections).

This is a two step issue 1 query 2 orderby. Currently this is my sql (not working): Only if I remove the complete 'meta_query' => array posts with no content for datum_event are shown, the first inner array does work to query posts from the past (compare' => '<=').

$args = array(
    'post_type' => array(
        'nieuws',
        'blog',
        'agenda'
    ),
    'meta_query' => array(
        'relation' => 'OR',
        // if has content for datum_event:
         array(
            'key'     => 'datum_event',
            'value'   => date('Ymd'),
            'compare' => '<=',
             // use datum_event to orderby:
            'meta_key' => 'datum_event',
            'meta_type' => 'DATE',
            'orderby' => 'meta_value',
            'order' => 'ASC',
        ),
        // if has no content for datum_event:
        array(
            'key' => 'datum_event',
            'meta_compare' => 'NOT_EXISTS',
            // order by date:
            'orderby' => 'date',
        ),
    ),
);
  • order and orderby are not valid arguments within a meta query, those are ignored. That aside, what you want can't be done with WP_Query. You have to write your own SQL query, or use the SQL filters, like posts_where and posts_join. – Milo Feb 1 at 4:48
  • Too bad. How about order by meta value and if meta value does not exist put post last? Can this be done (instead of using 'date' only meta value)? – Ludo Feb 1 at 10:03

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.