I’m working a on a widget that will display posts published between two dates, for example Jan 15 and March 15, but I don’t know how do it.
I saw a few solutions that mention query_posts() but I don’t think that’s a good solution. So I’m open to any suggestions how to do this.
At the moment I’m thinking using pre_get_posts, WP_Query, or get_posts and I tried with this line of code:
function my_home_category( $query )
{
if ( $query->is_home() && $query->is_main_query() )
{
$query->set( 'day', '15');
}
}
add_action( 'pre_get_posts', 'my_home_category' );
But this returns all the posts published on 15th of any month. I know I can set something like:
$query->set( 'monthnum', '1');
and get posts published on 15th January, but I want to get all posts published between 15th Jan – 15th March, and I don’t know how to achieve that.
It doesn’t have to use pre_get_posts, it could be get_posts or WP_Query, I’m just looking for a simple way to do it.
WP_Query offers a date_query parameter, allowing you to set a range with before and after.
https://developer.wordpress.org/reference/classes/wp_query/#date-parameters
I’ve just answered here an answer with a combination of both methods, from the original question and the answer from @johnnyd23:
You can replace ‘parse_query’ with ‘pre_get_posts’ and I think you’ll get the same result.