questions

How to apply pagination for custom endpoint request in WP?

Rate this post

I have created a custom restful API endpoint in WordPress which returns the JSON with the only required fields.

So with this one when I go to the example.com/wp-json/wl/posts, it returns 5 posts as I have limited the number of the posts.

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',
    ]);

});

But I also want to add the pagination, so if I add ?page=2 , it should return another 5 posts.

How can that be archived?

 

✔️Solution:

When visiting /?rest_route=/ or /wp-json/wp/v2/pages you can drill down into ie. wp/v2/pages/endpoints/0/args then check with page and per_page

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

Publish arguments for reference

We can define and publish these as arguments. This is not required but they are now in line with posts and pages

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",
      ]
    ],
  ]);
});

Fetch arguments

As get_posts has its own logic and it uses WP_Query in the end let’s use WP_Query for the better.

function wl_posts() {
  $args = [];

  if (isset($_REQUEST['per_page'])) {
    $args['posts_per_page'] = (int) $_REQUEST['per_page'];
  }
  if (isset($_REQUEST['page'])) {
    $args['page'] = (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;
}

Leave a Reply

Your email address will not be published.

Back to top button