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
$args = array(
'date_query' => array(
array(
'after' => 'January 1st, 2015',
'before' => 'December 31st, 2015',
'inclusive' => true,
),
),
);
$query = new WP_Query( $args );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With