教程:WP_Query查询有偏移量如何分页

在我做我的iebase主题时,也就是本站目前使用的主题。在做分页时出现一个错误。就是在自定义WP_Query查询需要分页的时候。出现一个偏移,也就是下一页里有上一页的一篇文章。下面记录下我的解决方法,写篇文章记录下,也为那些主题开发者做一个提示。代码如下:

$current_page = get_query_var('paged');
$current_page = max( 1, $current_page );

$per_page = 12;
$offset_start = 1;
$offset = ( $current_page - 1 ) * $per_page + $offset_start;
$post_list = new WP_Query(array(
    'cat' => -15,
    'posts_per_page' => $per_page,
    'paged' => $current_page,
    'offset' => $offset, // Starts with the second most recent post.
    'orderby' => 'date', // Makes sure the posts are sorted by date.
    'order' => 'DESC', // And that the most recent ones come first.
));
// Manually count the number of pages, because we used a custom OFFSET (i.e.
// other than 0), so we can't simply use $post_list->max_num_pages or even
// $post_list->found_posts without extra work/calculation.
$total_rows = max( 0, $post_list->found_posts - $offset_start );
$total_pages = ceil( $total_rows / $per_page );
if ( $post_list->have_posts() ):
    while ( $post_list->have_posts() ):
        $post_list->the_post();

        // loop output here
    endwhile;
    echo paginate_links( array(
        'total' => $total_pages,
        'current' => $current_page,
    ) );
endif;
wp_reset_postdata();

这样就能解决偏移问题了。注意:本教程为特定教程,给需要有基础的朋友使用。不会使用的请路过或是请博主帮忙解决。

本文已在Ie主题99839发布

文章来源:https://ietheme.com/paginate-wp-query-with-an-offset.html


撰写评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

加入我们

注册完成!

密码重置

请输入您的邮箱地址。 您将收到一个链接来创建新密码。

检查你的邮件中的确认链接。