REST API支持一次最多捕获100篇文章,因此您必须每100篇文章再调用一次。
从开始wp_remote_get()
100个职位。在阅读时,请继续检索此页的正文并对其进行解码:
$transcripts = wp_remote_get(\'http://example.com/wp-json/wp/v2/transcript/?per_page=100\');
$transcriptsBody = wp_remote_retrieve_body($transcripts);
$transcriptsDecoded = json_decode($transcriptsBody, true);
接下来,确定当前存在100个页面中的多少个页面:
$numPages = wp_remote_retrieve_header($transcripts, \'x-wp-totalpages\');
然后,如果有多个页面,请抓取每个附加页面。从第2页开始,因为你已经抓到了第1页。
if($numPages > 1) {
for($i=2; $i<($numPages+1); $i++) {
// Identify the next endpoint to call
$nextUrl = \'http://example.com/wp-json/wp/v2/transcript/?per_page=100&page=\' . $i;
}
// Remote_get that endpoint
$nextPage = wp_remote_get("$nextUrl");
// Set a variable variable name for the next page
$bodyVar = \'transcripts\' . $i;
// Get the body of the current page
$$bodyVar = wp_remote_retrieve_body($nextPage);
// Set a variable variable name for the decoded body
$decodeVar = \'transcriptsDecoded\' . $i;
// Decode the JSON
$$decodeVar = json_decode(${$bodyVar}, true);
// Finally, merge the posts into the existing decoded array
$transcriptsDecoded = array_merge($transcriptsDecoded, $$decodeVar);
}
现在,您将拥有一个包含所有帖子的PHP数组,无论帖子有多少。
请注意,如果使用REST API进行拉取,并将帖子保存到其他数据库中,则会有一个静态副本。如果有人更新、删除或添加到原始站点,您的副本将不会同步。因此,更常见的做法是将REST API调用构建到要显示内容的另一个站点的代码中,这样它就可以访问并获取您想在此时此地显示的特定内容。(理想情况下,将其缓存至少几个小时或几天,这样您就不必一直等待数据重新加载。)