So I am working with the WordPress REST API and I would like to pull in all the posts from the last 2 weeks
, so approximately 14 days.
In the WordPress REST API arguments, they have a before
and after
argument (https://developer.wordpress.org/rest-api/reference/posts/#example-request) that I might be able to utilize, but I'm unsure how to take this approach.
The WordPress REST API endpoint is being called using $response = wp_remote_get
.
Here is my completed method to pull in ALL post for now:
public function get_posts_via_rest_api(): array
{
$page = get_option('global_posts_page');
if (!$page) {
$page = 1;
}
try {
$response = wp_remote_get(
'https://example.com/wp-json/wp/v2/posts?page=' . $page
);
if ((!is_wp_error($response)) && (200 === wp_remote_retrieve_response_code($response))) {
$response_body = json_decode(
$response['body'],
false,
512,
JSON_THROW_ON_ERROR
);
return empty($response_body) ? [] : $response_body;
}
} catch (Exception $e) {
error_log(
print_r(
'Error: ' . $e,
true
)
);
return [];
}
}
WP_Query
would suffice