php 如何在wordpress中为自定义端点请求应用分页?

b1payxdu  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(132)

我在WordPress中创建了一个自定义的REST API端点,它返回JSON,只包含必需的字段。
因此,当我访问example.com/wp-json/wl/posts时,它返回5个帖子,因为我限制了帖子的数量。

function wl_posts() {
    $args = [
        'numberposts' => 99999,
        'post_type' => 'post'
    ];

    $posts = get_posts($args);

    $data = [];
    $i = 0;

    foreach($posts as $post) {
        $data[$i]['id'] = $post->ID;
        $data[$i]['title'] = $post->post_title;
        $data[$i]['content'] = $post->post_content;
        $data[$i]['slug'] = $post->post_name;
        $data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
        
        $i++;
    }

    return $data;
}

add_action('rest_api_init', function() {
    register_rest_route('wl/v1', 'posts', [
        'methods' => 'GET',
        'callback' => 'wl_posts',
    ]);

});

但是我还想添加分页,所以如果我添加?page=2,它应该会返回另外5篇文章。
怎么存档呢?

alen0pnh

alen0pnh1#

访问/?rest_route=//wp-json/wp/v2/pages时,可以深入到ie。wp/v2/pages/endpoints/0/args然后检查pageper_page

curl http://YOUR-SITE/wp-json/wl/v1/posts/?per_page=1&page=2

发布参数参考

我们可以定义并发布这些参数。这是不需要的,但他们现在符合职位和网页

add_action('rest_api_init', function() {
  register_rest_route('wl/v1', 'posts', [
    'methods' => 'GET',
    'callback' => 'wl_posts',
    'args' => [
      'page' => [
        'description' => 'Current page',
        'type' => "integer",
      ],
      'per_page' => [
        'description' => 'Items per page',
        'type' => "integer",
      ]
    ],
  ]);
});

获取参数

由于get_posts有自己的逻辑,它最终使用WP_Query,因此让我们使用WP_Query更好。

function wl_posts() {
  $args = [];

  if (isset($_REQUEST['per_page'])) {
    $args['posts_per_page'] = (int) $_REQUEST['per_page'];
  }
  if (isset($_REQUEST['page'])) {
    $args['paged'] = (int) $_REQUEST['page'];
  }

  $args['post_type'] = 'post';

  $get_posts = new WP_Query;
  $posts= $get_posts->query( $args );

  $data = [];
  $i = 0;

  foreach($posts as $post) {
    $data[$i]['id'] = $post->ID;
    $data[$i]['title'] = $post->post_title;
    $data[$i]['content'] = $post->post_content;
    $data[$i]['slug'] = $post->post_name;
    $data[$i]['featured_image']['thumbnail'] = 
      get_the_post_thumbnail_url($post->ID, 'thumbnail');

    $i++;
  }

  return $data;
}

相关问题