pagination in WP rest api

时间:2019-09-16 作者:Ajay Paudel

我们已经制作了一个自定义API来按降序获取所有帖子,我们希望在该API中添加分页。我已经阅读了其他问题和答案,但没有领会其中的意思。谁能用一个简单的分页代码向我解释一下,这样我就能理解它是如何工作的?以下是我迄今为止所做的代码:

define(\'API_ENDPOINT_VERSION\',1);

//flush the rewrite rules on plugin activation

function apiendpoint_activate()
{
    flush_rewrite_rules();
}
register_activation_hook(__FILE__,\'apiendpoint_activate\');

function apiendpoint_register_endpoints(){
    register_rest_route(
        \'api/v1\',
        \'/post\',
        [
            \'methods\' => \'GET\',
            \'callback\' =>\'api_get_post\',
        ]
    );

}
add_action(\'rest_api_init\',\'apiendpoint_register_endpoints\');

function api_get_post($request){
    $ar = array( \'post_type\'=>\'post\',
         \'posts_per_page\'=>15,
         \'orderby\' => \'date\',
         \'order\' => \'DESC\',
       );
    $posts = get_posts($ar);
    //var_dump($posts);
    //exit;
    $a = array();

    if($posts){
        foreach ($posts as $post) {


        $a[]= array(   
        \'title\'=>$post->post_title,
         \'link\'=>get_the_permalink($post->ID),
         \'category\'=>get_the_category($post->ID),
         \'published_date\'=>get_the_date(\'l, F j, Y\',$post->ID),
          \'guid\'=>$post->guid,
          \'image\'=>get_the_post_thumbnail_url($post->ID,\'large\'),
           \'description\'=>$post->post_excerpt,
           \'source\'=>"Nepaljapan"
        //\'img\'=>$img
        );
        }
        return $a;
    }
} 

1 个回复
SO网友:Ajay Paudel

define(\'API_ENDPOINT_VERSION\', 1);

//flush the rewrite rules on plugin activation

function apiendpoint_activate() {
    flush_rewrite_rules(); } register_activation_hook(__FILE__, \'apiendpoint_activate\');

function apiendpoint_register_endpoints() {
    register_rest_route(
        \'api/v1\',
        \'/post\',
        [
            \'methods\' => \'GET\',
            \'callback\' => \'api_get_post\',
        ]
    );

} add_action(\'rest_api_init\', \'apiendpoint_register_endpoints\');

function api_get_post($request) {
    $ar = array(\'post_type\' => \'posts\',
        \'posts_per_page\' => 15,
        \'orderby\' => \'date\',
        \'order\' => \'DESC\',
        \'paged\' => ($_REQUEST[\'paged\'] ? $_REQUEST[\'paged\'] : 1) 
); 

$posts = get_posts($ar); //var_dump($posts); //exit; $a = array();

if ($posts) {
    foreach($posts as $post) {


        $a[] = array(
            \'title\' => $post -> post_title,
            \'link\' => get_the_permalink($post -> ID),
            \'category\' => get_the_category($post -> ID),
            \'published_date\' => get_the_date(\'l, F j, Y\', $post -> ID),
            \'guid\' => $post -> guid,
            \'image\' => get_the_post_thumbnail_url($post -> ID, \'large\'),
            \'description\' => $post -> post_excerpt,
            \'source\' => "Nepaljapan"
            //\'img\'=>$img
        );
    }
    return $a; } 
}
调用API调用如下:

/wp json/api/v1/post?分页=1

将分页值增加1以获取下一个分页帖子。这是我们得到的正确答案,并且对我起到了作用