Retrieving posts based on a particular date or time duration is a common use case during development. To retrieve the posts or comments by date and time, you need to use the date query. The date query provides several parameters which allows you to use a time and date as conditional arguments while fetching posts.
Fetching Posts with Date Query
To fetch posts conditionally, we need to use the WP_Query function with the specified arguments. To get posts bound by a date or time limit, we need to specify a conditional date query. For example, to get all posts, published in the last week, you would have to frame your date query as follows:
$last_week_posts = new WP_Query( array('date_query' => array( array ( 'after' => '1 week ago',) ) ));
To get posts after 1st January 2014, and before 1st March 2014 your date query would be:
'date_query' => array( array ( 'year' => 2014, 'day' => 1, array('month' => array(1, 6 ), 'compare' => 'BETWEEN', ), ));
There are several conditions you can use to frame your query. You can use, year, month, day, time till seconds, etc. For additional details read, Date Parameters in WordPress Queries.
Fetching Comments with the Date Query
You can also use the date query to get the comments according to a time duration. As an example, say you had to get the comments which were not older than 30 days. You can use the get_comments function to get the comments, and use the data_query as one of the arguments for the function.
Thus to get recent comments (approved comments, posted at the most 30 days ago) , you have to do the following:
//set the arguments $args = array( 'orderby' => 'date', 'status' => 'approve', 'order' => 'DESC', 'date_query' => array( array( 'after' => '30 days ago', ) ) ); // get the comments using the arguments $comments = get_comments($args);
Date queries are a very important and useful feature which allows you to retrieve posts and comments based on a date and time parameter.