如何通过REST API获取所有自定义贴子类型的贴子?

时间:2019-09-19 作者:K. Pro

我在wordpress网站上有CPT成绩单。并在CPT成绩单中创建250个帖子。

现在,我想获取所有的转录本数据,并想使用RESTAPI url存储在另一个数据库中http://example.com/wp-json/wp/v2/transcript/

以及

使用CURL的HTTP请求

$ch = curl_init();
$url = \'http://example.com/wp-json/wp/v2/transcript/\'; 
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
return curl_exec($ch);
curl_close($ch);
但这份报告只有10份成绩单,

请帮助我,如何检索所有成绩单帖子数据。

2 个回复
SO网友:WebElaine

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调用构建到要显示内容的另一个站点的代码中,这样它就可以访问并获取您想在此时此地显示的特定内容。(理想情况下,将其缓存至少几个小时或几天,这样您就不必一直等待数据重新加载。)

SO网友:Luke Gedeon

您可以按照其中一条评论中的建议添加&filter[posts_per_page]=250 但这是一个相当大的反应,可能在任何一端都不会得到很好的处理。

可能是建议的更好的方法under pagination 是要添加?per_page=100 在第一次请求时,然后使用?per_page=1&page=2

如果您发现一次100页仍然很高,请尝试较低的数字,并根据需要请求额外的页面。

如果您需要有关循环和/或串联的帮助,请告诉我,我可以对此进行扩展。