Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom WP_Query to get posts from a specific date range from a range of years.
<?php
$dates = ['relation'=>'OR'];
$x = 1;
while( $x <= 5 ) :
$currentDate = new DateTime();
$previous_date = $currentDate->sub( new DateInterval( "P{$x}Y" ) );
$previous_year = $previous_date->format('Y');
$currentDate = new DateTime();
$previous_days = $currentDate->sub( new DateInterval('P15D') );
$previous_day = $previous_days->format('m-d');
$currentDate = new DateTime();
$future_days = $currentDate->add( new DateInterval('P15D') );
$future_day = $future_days->format('m-d');
$dates[] = [
'after' => $previous_year . '-' . $previous_day,
'before' => $previous_year . '-' . $future_day,
'inclusive' => true,
];
$x++;
endwhile;
$args = [
'date_query' => $dates
];
$r = new WP_Query($args);
/*
[request] => SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.ID FROM wp_posts WHERE 1=1 AND (
( wp_posts.post_date >= '2019-08-25 00:00:00' AND wp_posts.post_date <= '2019-09-24 23:59:59' )
OR
( wp_posts.post_date >= '2018-08-25 00:00:00' AND wp_posts.post_date <= '2018-09-24 23:59:59' )
OR
( wp_posts.post_date >= '2017-08-25 00:00:00' AND wp_posts.post_date <= '2017-09-24 23:59:59' )
OR
( wp_posts.post_date >= '2016-08-25 00:00:00' AND wp_posts.post_date <= '2016-09-24 23:59:59' )
OR
( wp_posts.post_date >= '2015-08-25 00:00:00' AND wp_posts.post_date <= '2015-09-24 23:59:59' )
) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 12
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.