0

Thanks for taking the time to read this. I've been struggling with a meta_query for an events site I'm working on.

I have used ACF to create a field for date start and date end, but not all events will have a date.

What I'm trying to achieve, is when you go to the archive or tax view, the first thing you see are the posts that have a date assigned, in order from today's date into the future. Then after those dated events have been output, to cycle through all empty date posts.

So far I have the below in my functions.php file. This kind of works, but in the wrong order. So the correct events that are dated are output and in the right order. But only after the null valued items have output. I thought that may be because of the ordering in the arrays themselves, so moved the date ordered array to the end. That had no effect.

$query->set( 'post_type', 'courses' );
$query->set( 'meta_query', array(
    'relation' => 'OR',
    array(
        'key'        => '_course_date_from',
        'compare'    => '=',
        'value'      => '',
    ),
    array(
        'key'     => '_course_date_from',
        'compare' => '>=',
        'value'   => date('Ymd'),
    )
) );
$query->set( 'orderby', 'meta_value title' );
$query->set( 'order', 'ASC' );

Thanks for your time. Ben.

0

Not sure if it helps you any, but I think splitting this into two simple queries is a simple way to do it but then requires some extra work to be able to display two $query results sequentially. This may also be better for users as you could make it clear that you're showing them two lists with and without dates?

The logic that you have now says: 'date_from is empty OR date_from >= today, and sort these by title'. That's a bit different to what you want.

The logic you describe is more easily described as two lists that you want to show: (i'm assuming it's ok to use date_from only and not also check date_to for being empty or not, and assuming that if date_from is empty you want to show them going back from today):

  1. (date_from IS NOT empty) AND date_from >= today, order by date_from ASC
  2. date_from IS empty, order by date_from DESC

If this sounds like a good direction, it should be possible to figure out how to get the two query results into one, there's a rather complicated example here: https://stackoverflow.com/questions/23555109/wordpress-combine-queries, but happy to help with code as it sounds like a useful thing to be able to do.

  • Thanks MozBoz, this has I think put me onto the right sort of lines. Cheers for the advice. – Ben Jul 2 '20 at 20:37

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.