Last active
October 26, 2016 13:33
-
-
Save andreilupu/28d99b81536181a312f820f9be5d077b to your computer and use it in GitHub Desktop.
How to loop the API results which are paginated
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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