0

I'm writing an on this day function which should show the X number of posts for the current day and month.

How can I add a fallback to the query if there are no posts, to show the next available day of posts?

These are the arguments I'm passing to the current day query.

    $onThisDay_args = array(
      'post_type' => array('on-this-day'),
      'posts_per_page' => $postlimit,
      'date_query' => array(
        array(
          'month' => date( 'n', current_time( 'timestamp' ) ),
          'day' => date( 'j', current_time( 'timestamp' ) )
        ),
      )
    );

The only way I can think of executing this requirement is if the results from the first query equal null or 0, then run the second query.

If that is the case, how do I modify the date_query arguments to fallback to the previous day of available posts?

Thanks.

1 Answer 1

1

How to solve this depends very much how you store it.

In general I would be aware of letting WordPress handle historical dates, of broad range, as post dates. There are various limitations that you can check on this site or eg. trac.

Date query for yesterday

If you create a datetime object with:

 $dto = DateTime::createFromFormat( 'Y-n-j', current_time( 'Y-n-j' ) );

where the timezone is included in the current_time(), then you can try to set it to the day before with:

 $dto->modify( 'yesterday' );

The month and day for yesterday should be accessible with:

'date_query' => [
    [
        'month' => $dto->format('n'),
        'day'   => $dto->format('j'),
     ],
],

For 2 days before we can try

$dto->modify( '-2 days' );

and so on

Date query for the current date or the previous available date

If you use the same year for all events, then you can use:

'date_query' => [
    [
        'before'      => current_time( 'Y-n-j' ),
        'inclusive'   => true,
     ],
],

Alternatives

For a very sparse month-day list, one could try to group posts by month and day to find the previous available post date. But this would need a custom query.

One could also use a custom database table to store the dates, for more flexibility, but that also needs a custom building.

Many event plugins store the dates in the post meta, and use meta_query in WP_Query to filter through it. But this might not scale well for large number of posts.

We could even use a custom taxonomy to store the month-day, but then the month-day ordering might get tricky.

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.