Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to loop the API results which are paginated
<?php
/**
* Let's imagine that we need the issues number from an github organization
* The issues API results are limited to 100 per page so we need to call this recursively
* $offset (int) = the number of pages to skip for the current request
*/
function request_issues_number( $offset = 0 ) {
$page = 1;
if ( ! empty( $offset ) ) {
$page = $offset + 1;
}
$response = $this->github_request( '/orgs/:org/issues?page=' . $page . '&state=all&per_page=100' );
if ( 'OK' !== wp_remote_retrieve_response_message( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
wp_send_json_error( $response );
}
$json = wp_remote_retrieve_body( $response );
$issues = json_decode( $json );
$count = 0;
if ( ! empty($issues) ) {
foreach ( $issues as $issue ) {
$count++;
}
}
if ( !empty( $offset ) ) {
$count = (int)$count + (int)$offset * 100;
}
$issues_nr = $count;
if ( count( $issues ) > 99 ) {
$issues_nr = $this->request_issues_number( $page );
}
return $issues_nr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment