15

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.

Mentalhead
  • 1,501
  • 5
  • 20
  • 28

2 Answers2

33

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 );
Erenor Paz
  • 3,061
  • 4
  • 37
  • 44
johnnyd23
  • 1,665
  • 2
  • 13
  • 24
0

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.

etruel
  • 71
  • 3