Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top