您如何限制per_page结果并显示自定义WP REST API端点的分页链接



我已经设置了一个自定义的WP REST API路由,我需要帮助将结果限制为每个页面5,然后具有分页链接以显示下一页等。

我尝试在参数数组中添加'per_page => 5',但是URL的结果没有任何改变。我似乎也无法弄清楚如何包含分页。抱歉,这是我第一次。

function staffSearchEndpoint(){
    register_rest_route('staffbio/v1', 'staffsearch', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => 'staffSearchJSONResults',
    ));
}
function staffSearchJSONResults($data) {
    $staffBio = new WP_Query(array(
        'post_type' => 'staff_bios',
        's' => $data['term'],
        'orderby' => 'title',
        'order' => 'asc'
    ));

如果您可以让我知道在$staffBio array中添加的内容,或其他将不胜感激的其他内容。另外,如果您的答案需要JavaScript,请仅使用普通JS,请不要使用jQuery。

看来,您在每个页面上使用了错误的WP查询参数。您需要在WP_Query参数中使用'posts_per_page' => 5,而不是'per_page => 5'

,您的staffSearchJSONResults功能将是:

function staffSearchJSONResults($data) {
$staffBio = new WP_Query(array(
    'post_type' => 'staff_bios',
    'posts_per_page' => 5,
    's' => $data['term'],
    'orderby' => 'title',
    'order' => 'asc'
));

为分页,我建议使用offset参数。

说您在staff_bios中有帖子总数,posts_per_page的值和默认offset值将为0

分页的基本逻辑表示形式将是:

$pagination_number = 1; //Default pagination number, change as per pagination number
$total_posts = 30;
$posts_per_page = 5;
//This will change based on pagination number, it indicate how many post to skip
$offset = ($pagination_number - 1) * $posts_per_page;  
$data = WP_Query(array(
'post_type' => 'staff_bios',
'posts_per_page' => $posts_per_page,
's' => $data['term'],
'orderby' => 'title',
'order' => 'asc',
'offset' => $offset,
));
$total_pagination = $total_posts/$posts_per_page; //(1, 2, 3 ,4 , 5, ....)
//LOOP THGOUGH DATA

您可以在此处检查所有WP_QUERY参数:https://www.billerickson.net/code/wp_query-arguments/

最新更新