【问题标题】:Loading Posts using WordPress Rest API使用 WordPress Rest API 加载帖子
【发布时间】:2017-05-08 15:03:42
【问题描述】:

我正在使用 WP Rest API 来加载帖子。我正在使用以下代码。

jQuery('document').ready(function)(){
jQuery('#btn').on('click', function() {
  jQuery.ajax({
        type: 'GET',
        url: "http://localhost/umar/api/wp-json/wp/v2/posts",
        data: { action: 'createHTML' },
        success: function(data) {
            var obj = JSON.stringify(data);
            var test = jQuery.parseJSON(obj);
            createHTML(test);
            jQuery('#btn').hide();
           }
         });
       });
     });

    function createHTML(postData) {
      var ourHTMLString = '';
      for(i=0; i<postData.length; i++) {
        ourHTMLString += '<p>' + postData[i].title.rendered + </h2>;
        ourHTMLString +=  postData[i].title.rendered;
      }
    jQuery(".entry-content").append(ourHTMLString);
   }

我有 50 个帖子,我想一次加载 7 个帖子。因此,当用户单击“加载更多”按钮时,他应该能够加载 7 个帖子,并且该过程再次继续进行,最后按钮被隐藏。我应该添加什么功能来实现这一点?

【问题讨论】:

  • 第一:请求总发帖量。第二:将其存储在变量中。第三:使用另一个变量来计算加载的帖子数量。然后您可以随后加载下一个 7,将计数器增加 7 等,直到达到总量。

标签: jquery ajax wordpress


【解决方案1】:

您应该使用 WP 提供的分页功能,如 链接here

所以对于获取帖子应该是

/wp/v2/posts?per_page=7&page=1

每页 - Number of records per page

页面 - page number - to be determined from Rest API Response as given below

同样在 REST API Response 中,你会得到两个 Header Response

X-WP-Total:集合中的记录总数

X-WP-TotalPages:包含所有可用记录的总页数

因此使用X-WP-TotalPages 您将能够知道是否必须获取下一页。

因此代码可能看起来像

<button data-page="1" data-per-page="7">Load More </button> 
<script>
var $wpURL="http://localhost/umar/api/wp-json/wp/v2/posts?";

$('#btn').on('click', function() {

  var $this = $(this);
  var nextPageToRetrieve = $this.data('page')+1;
  var dataPerPage = $this.data('per-page');
  $wpURL = $wpURL + "per_page="+ nextPageToRetrieve+"&page="+ dataPerPage;

  $.ajax({
        type: 'GET',
        url: $wpURL,
        data: { action: 'createHTML' },
        function(data, textStatus, request){
          request.getResponseHeader('X-WP-TotalPages');
          request.getResponseHeader('X-WP-Total');
          //Figure out the logic whether the next fetch should happen :) 
          // and disable the button if so.
   },
    error: function (request, textStatus, errorThrown) {
           //FailSafe for WP API Failing
   }
           });
         });
</script>

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 2018-04-05
    • 2018-08-02
    • 1970-01-01
    • 2020-11-23
    • 2021-04-06
    • 2018-02-17
    • 2017-10-12
    • 2010-11-24
    相关资源
    最近更新 更多