繁体   English   中英

使用WP REST API WordPress插件将帖子添加到我的PHP页面

[英]Using WP REST API WordPress plugin to add posts to my PHP page

我正在重做我的个人网站,并希望为wordpress的最新帖子添加一个部分。 这样我可以在主索引页面上有3个帖子,我可以用手机更新,而无需编写新内容。我安装了WordPress插件WP REST API。 我甚至使用domainname / 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-->

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM