簡體   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