0

I have a custom date field that is optional. If a date is not provided, the item should be first in the items returned by WP_Query. Example:

1st: entry with no date
2nd: entry with date 1 March 2023
3rd: entry with date 1 February 2023
4th: entry with date 1 January 2023

These are the args I'm using:

'meta_key' => 'custom_date',
'orderby' => array(
    'date_empty' => 'ASC',
    'custom_date' => 'DESC'
),
'meta_query' => array(
    'relation' => 'OR',
    'date_empty' => array(
        'key' => 'custom_date',
        'value' => '',
        'compare' => '='
     ),
     'date_not_empty' => array(
         'key' => 'custom_date',
         'value' => '',
         'compare' => '!='
      )
),

However the order is showing with the dates in the wrong order:

1st: entry with no date
2nd: entry with date 1 January 2023
3rd: entry with date 1 February 2023
4th: entry with date 1 March 2023

It seems the second orderby clause is having no impact. I have checked that the date clause works fine when I remove the first clause.

2
  • Did you ever get any further with this?
    – Chris Pink
    Commented Feb 14 at 14:39
  • @ChrisPink I was able to get it working with a few changes - have shared the solution below. Hope this helps.
    – Space
    Commented Feb 14 at 17:30

1 Answer 1

2

I ended up using these WP_Query arguments:

'orderby'    => 'meta_value',
'order'      => 'ASC',
'meta_key'   => 'custom_date',
'meta_query' => array(
    'relation'    => 'OR',
    'date_clause' => array(
        'key'     => 'custom_date',
        'value'   => date('Ymd'),
        'type'    => 'DATE',
        'compare' => '>=',
    ),
    'date_empty'  => array(
        'key'     => 'custom_date',
        'value'   => '',
        'compare' => '=',
    )
)

For my use case I wanted to list upcoming events (but not past ones). For year-round events these had no set date and I wanted these at the top.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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