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(

            return empty($response_body) ? [] : $response_body;
    } catch (Exception $e) {
                'Error: ' . $e,

        return [];
  • To be clear, is the WordPress REST API which you are querying separate from the installation on which you're running this code? If they are the same installation, there's no reason to use the REST API - a WP_Query would suffice
    – bosco
    Jul 16, 2022 at 23:22
  • 1
    @bosco, they are different websites, I'm pulling in posts from one of our websites to the other.
    – DevSem
    Jul 17, 2022 at 0:00

1 Answer 1


Use PHP's strtotime() function to retrieve the timestamp for the date fourteen days ago, then date() to cast it into an ISO 8601-compliant string which can be passed into the after parameter.

I'm using sprintf() here to insert the date just to keep things a bit cleaner and avoid a mess of concatenation.

$url = sprintf(
  date( 'c', strtotime( '-14 days' ) ),
  • Thanks so much @bosco, I'll attempt this now!
    – DevSem
    Jul 17, 2022 at 0:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.