0

I am trying to query my post for several date ranges which are specifically posts that are published in 24 hours, within 7 days, posts that are two weeks old, and posts older than 2 weeks.

I am able to easily query the posts if I am trying to query a specific date range for example, posts from 24 hours.

What I am struggling with right now is I am not certain how to query the posts when two date ranges are selected. For example, if a user tried to filter and see the posts that are posted within 24 hours and posts that are older than two weeks.

Here is the structure of the array that I use for the date range filter:

Array
(
    [0] => 24-hours-after
    [1] => 1-week-after
    [2] => 2-weeks-before
)

Then my current code is:

$the_date = end( $_POST['date_range'] );

$the_date_sep = explode( '-', $the_date );

$args['date_query'] = array(
    array(
        $the_date_sep[2] => $the_date_sep[0] .' ' .$the_date_sep[1]  .' ago'
    ),
        'inclusive' => true,
);

I am using the end function to get the last filter selected but obviously this is not an efficient way to go because it disregards other selected filter and if I try to filter posts from different date range like posts from 24 hours ago and posts that are two weeks old.

What is the efficient way to have this implemented where I can filter Wordpress posts based on the dates?

Thank you!

0

You can use multiple date ranges in your query like so:

$args['date_query'] = array(
    'relation' => 'OR',
    array(
        'after' => '-24 hours',
    ),
    array(
        'after' => '-1 week',
    ),
    array(
        'before' => '-2 weeks',
    )
);

This will get you posts that were published in any of these ranges.

So now you have to build such array based on your filter data.

  • Thank you very much. This pointed me to the right way. :) – drifter Mar 8 at 10: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.