Paulund

Get Posts Between Certain Dates WordPress REST API

When building your WordPress theme using the REST API one of the pages you might want to correct is the Post archives page that displays all the posts for a certain month. Using the WP_Query object you will do this by passing in a date_query parameter with a after and before argument.


$args = array(
	'date_query' => array(
		array(
			'after'     => 'January 1st, 2017',
			'before'    => array(
				'year'  => 2017,
				'month' => 2,
				'day'   => 28,
			),
			'inclusive' => true,
		),
	),
	'posts_per_page' => -1,
);
$query = new WP_Query( $args );

Using the REST API you can perform the same search by using the after and before querystring parameters that will limit response to posts published before a given ISO8601 compliant date. Using the DateTime object you can easily do this by using the below code.


$date = new DateTime();
$afterDate = $date->modify('first day of this month')->format('Y-m-d\TH:i:s');
$beforeDate = $date->modify('last day of this month')->format('Y-m-d\TH:i:s');

https://example.com/wp-json/wp/v2/posts?after=' . $afterDate . '&before=' . $beforeDate;

This will return all the posts you need within the date range.

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring