【问题标题】:Getting a list of all objects from Wordpress REST API从 Wordpress REST API 获取所有对象的列表
【发布时间】:2019-12-13 20:24:53
【问题描述】:

我想收到来自 Wordpress REST API 的 10 个帖子的标题和链接。

我的代码只获取 JSON 数组中的第一个对象。我知道这是因为 [0],但我正在努力寻找一种解决方案来显示所有对象的所需值。

<div class="mypanel">

       <script>
    $.getJSON('https://www.example.com/wp-json/wp/v2/posts', function(item) {       
        var text = `<li><a href="${item[0].link}"><h2>${item[0].title.rendered}</h2></a></li>`
        $(".mypanel").html(text);
    });
    </script>

      </div> 

我读到 $.map() 可能是我的问题的潜在解决方案,但无法弄清楚在这种情况下如何正确使用它。

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery json wordpress api


    【解决方案1】:

    我猜如果您在响应中获得了所有值,那么只需对其进行迭代:

    const perPage = 10; // 10 posts
    const url = 'https://www.example.com/wp-json/wp/v2/posts?per_page=' + perPage;
    const handleResponse = items => {
      let text = '';      
    
      items.forEach(item => {
        text += `<li><a href="${item.link}"><h2>${item.title.rendered}</h2></a></li>`;
      };
    
      $(".mypanel").html(text);
    };
    
    $.getJSON(url, handeResponse);
    

    请在此处找到 REST API 的所有其他参数:Arguments

    我希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      使用作为 WP api 一部分的分页。然后迭代它。只需将 ?per_page=10 添加到您的 URL:

       http://example.com/wp-json/wp/v2/posts?per_page=10
      

      更多:https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 2023-03-22
        • 2020-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        相关资源
        最近更新 更多