Categories
WordPress

WordPress REST API custom endpoint pagination

Within this example i will highlight how you can create custom route for posts queried by tag and employ pagination for finish result. For paginating query result it’s not suggested to make use of get_posts() method but WP_Query class.

so let’s create a custom route:

function wtc_register_rest_route() {
    
    register_rest_route( 'wtc/v1/', 'get-by-tag/(?P<slug>[a-z0-9]+(?:-[a-z0-9]+)*)/(?P<page>[1-9]{1,2})', array(
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'wtc_get_posts_by_tag',
            'args' => array(
                'slug' => array (
                    'required' => true
                ),
                'page' => array (
                    'required' => true
                ),            
            )
        ) 
    );

}
add_action( 'rest_api_init', 'wtc_register_rest_route' );

Within our example we are able to refer to this as url with pagination number in the finish: wtc/v1/get-by-tag/tag-name/2

Learn More: HOW TO SET WORD LIMIT ON THE_CONTENT() IN WORDPRESS

Next, let’s create callback method:

function wtc_get_posts_by_tag( WP_REST_Request $request ){
    // get slug and page number
    $slug = $request['slug'];
    $page = $request['page'];

    $term = get_term_by('slug', $slug, 'post_tag');

    $args = array(
            'tag__in'           => $term->term_id,
            'posts_per_page'    => $posts_per_page,
            'paged'             => $page,
            'orderby'           => 'date',
            'order'             => 'desc',
        );
    // use WP_Query to get the results with pagination
    $query = new WP_Query( $args ); 

    // if no posts found return 
    if( empty($query->posts) ){
        return new WP_Error( 'no_posts', __('No post found'), array( 'status' => 404 ) );
    }

    // set max number of pages and total num of posts
    $max_pages = $query->max_num_pages;
    $total = $query->found_posts;

    $posts = $query->posts;

    // prepare data for output
    $controller = new WP_REST_Posts_Controller('post');

    foreach ( $posts as $post ) {
        $response = $controller->prepare_item_for_response( $post, $request );
        $data[] = $controller->prepare_response_for_collection( $response );  
    }

    // set headers and return response      
    $response = new WP_REST_Response($data, 200);

    $response->header( 'X-WP-Total', $total ); 
    $response->header( 'X-WP-TotalPages', $max_pages );

    return $response;
}

Within our example we’re coming back in header final amount of pages and final amount of posts. get more information about WordPress Rest API.

By Ankit Panchal

I'm a WordPress consultant and Web developer. I like solving digital problems which help your business grow. I specialize in WordPress plugin development and frontend development and am available for hire.