Home > Blockchain >  Pull in ALL posts from the last two weeks using Rest API
Pull in ALL posts from the last two weeks using Rest API

Time:07-17

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 [];
    }
}

CodePudding user response:

The proper format for before or after is ISO8601 so 2022-07-16T20:33:00 In the below function, I set it to 2 weeks ago, 1 second after midnight. You can use date_format($date, 'Y-m-d\TH:i:s'); https://www.php.net/manual/en/datetime.format.php

public function get_posts_via_rest_api(): array {
    $page_number = get_option( 'global_posts_page' );
    if ( ! $page_number ) {
        $page_number = 1;
    }
    $today     = new DateTime(); // Today.
    $two_weeks = $today->sub( new DateInterval( 'P14D' ) ); // Two weeks ago.
    $after     = $two_weeks->format( 'Y-m-d\T00:00:01' ); // dateformat at midnight.
    try {
        $response = wp_remote_get(
            'https://example.com/wp-json/wp/v2/posts?page=' . $page_number . '&after=' . $after
        );
        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 ) ? array() : $response_body;
        }
    } catch ( Exception $e ) {
        error_log(
            print_r(
                'Error: ' . $e,
                true
            )
        );

    }
    return array();
}
  • Related