Get posts published between specific dates in wordpress

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.

Read More

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.

Related posts

Leave a Reply

2 comments

  1. I’ve just answered here an answer with a combination of both methods, from the original question and the answer from @johnnyd23:

    function my_home_by_period($query) {
        $query->set('date_query', array(
            array(
                'after'  => array(
                    'year'   => 2021,
                    'month'  => 10,
                    'day'    => 1,
                ),
                'before'     => array(
                    'year'   => 2021,
                    'month'  => 10,
                    'day'    => 31,
                ),
                'inclusive'  => true,
            )
        ));
    }
    add_action('parse_query', 'my_home_by_period');
    

    You can replace ‘parse_query’ with ‘pre_get_posts’ and I think you’ll get the same result.