Here I’ve written a function for you-
function the_dramatist_get_post_by_time_range( $args="" ) {
$date_query = array();
if ( $args === 'last 7 days') {
$date_query = array(
'after' => '1 week ago'
);
} else {
$month_ini = new DateTime("first day of last month");
$month_end = new DateTime("last day of last month");
$date_query = array(
array(
'after' => $month_ini->format('Y-m-d'),
'before' => $month_end->format('Y-m-d'),
)
);
}
$params = array(
'post_type' => 'attachment',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
// Using the date_query to filter posts from last week
'date_query' => $date_query
);
return get_posts($params);
}
Hope that’s gonna help. It’s gonna return you the posts object.
For ‘Last 7 Days’ use the function like-
the_dramatist_get_post_by_time_range('last 7 days')
and for “Last Month” use it as it is-
the_dramatist_get_post_by_time_range()
Please test it first wit various dates. If you find anything wrong please knock here. I think the date range can cause some problem. So please test it first.