Find us on Facebook

LightBlog
Responsive Ads Here

Thứ Sáu, 29 tháng 12, 2017

Why are my paginated posts always returning the same results?

Question:

I'm currently developing locally, and trying to get pagination for my posts page set up. At the moment I'm just trying to display one post per page, but of course this will increase in production.
Here's my query:
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : '1';

$posts_list = new WP_Query([
    'posts_per_page'    => 1,
    'offset'            => 0,
    'orderby'           => 'date',
    'order'             => 'DESC',
    'post_type'         => 'post',
    'suppress_filters'  => true,
    'paged'             => $paged
]);
And the pagination:
global $wp_query;

$big = 999999999; // need an unlikely integer
$translated = __( 'Page', 'mytextdomain' ); // Supply translatable string
    echo paginate_links( array(
    'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format'  => '?paged=%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total'   => $the_query->max_num_pages
) );
The pagination links are output fine, but the post displayed on each page is always the first one in the database.
Possibly worth noting is that I'm also using prettylinks, so the format of the paginated pages should be [domain]/news, [domain]/news/page/2, [domain]/news/page/3 etc...

Answer:

Found the culprit. I'd foolishly hard-coded the offset to be 0, which must have been overriding WordPress' query.
I changed:
$posts_list = new WP_Query([
    'posts_per_page'    => 1,
    'offset'            => 0,
    'orderby'           => 'date',
    'order'             => 'DESC',
    'post_type'         => 'post',
    'suppress_filters'  => true,
    'paged'             => $paged
]);
to:
$posts_list = new WP_Query([
    'posts_per_page'    => 1,
    'orderby'           => 'date',
    'order'             => 'DESC',
    'post_type'         => 'post',
    'suppress_filters'  => true,
    'paged'             => $paged
]);
and all is well.

Không có nhận xét nào:

Đăng nhận xét