Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get posts published between specific dates in wordpress

Tags:

php

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.

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.

like image 268
Mentalhead Avatar asked Mar 26 '15 09:03

Mentalhead


1 Answers

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 );
like image 114
johnnyd23 Avatar answered Nov 10 '22 21:11

johnnyd23