我正在重做我的个人网站,并想为wordpress最近的帖子添加一个部分。这样我就可以在我的主索引页上有3个帖子,我可以用手机更新,而不必编码新的东西。我安装了WordPress插件WP REST API。我甚至通过使用域名/wp-json/wp/v2/posts/检查了它,它显示了我创建的四个测试帖子。
我真的不知道JSON API的任何东西,但我有最困难的时间试图获取那些最近的帖子到我的特色帖子部分。我一直在互联网上寻找教程,希望能帮助我,但没有什么是真正显示在我的页面上的帖子。有人有什么建议吗?
根据你的问题,这里有一些一般的提示:
首先,您需要从example.com/wp-json/wp/v2/posts/
的WP中获取帖子。为此,您需要执行curl
GET请求。
看一下本教程,在PHP页面中发出请求时将示例域替换为您的站点。
结果是一个JSON对象。现在,对结果做一个json_decode()
,你应该有一个数组或对象。您可以通过对其进行迭代来显示结果。
下面是显示所有标题的示例:
<section id="blog">
<div class="container-fluid">
<div class="row">
FEATURED POSTS
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.bmcsquincy.com/featured_posts/wp-json/wp/v2/posts/',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$resp=json_decode($resp, TRUE);
//var_dump($resp);
foreach($resp as $post) {
echo '<h2>' . $post['title']['rendered'] . '</h2><br />';
}
?>
</div><!--END ROW-->
</div><!--END CONTAINER FLUID-->
</section><!--END SECTION BLOG-->
我使用http://www.bmcsquincy.com/featured_posts/wp-json/wp/v2/posts/,这就是我如何知道那部分是工作的。
对于我使用的PHP
<section id="blog">
<div class="container-fluid">
<div class="row">
FEATURED POSTS
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.bmcsquincy.com/featured_posts/wp-json/wp/v2/posts/',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
item1 => 'value',
item2 => 'value2'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
?>
</div><!--END ROW-->
</div><!--END CONTAINER FLUID-->
</section><!--END SECTION BLOG-->