Pagination Not Working When Used With WP_Query() `offset` Property

I have an archive page that pulls in posts using WP_Query(). On the homepage of the site it shows 16 of the custom post type posts, so on the archive I offset the archive page by 16 posts.

The code for this is:

$newsArticles = new WP_Query(array(
    'posts_per_page' = 16,
    'offset' = 16,
    'post_type'= 'news'
));

while(  $newsArticles-have_posts()){
        $newsArticles-the_post(); ?

        // HTML

?php } ?

However on this archive page the ?php echo paginate_links();? function to show the pagination pages doesn't work. When I click on the page numbers or use the next and previous arrows, but it just shows the same posts on each page.

The pagination code I'm using is:

p
    ?php echo paginate_links(array(
        'prev_text' = 'NEWER',
        'next_text' = 'OLDER',
    ));?
/p

Does anybody know how I get the pagination to work with the WP_Query() property offset so the archive pagination behaves like a normal archive page (with pagination) ?

Topic offsets loop wp-query pagination custom-post-types Wordpress

Category Web


I would use something like this :

$prev_link = get_previous_posts_link( '« ' . __( 'Previous Page' ) );
$next_link = get_next_posts_link( __( 'Next Page' ) . ' »' );

if ( $prev_link || $next_link ) {

$pagination  = $prev_link ? sprintf( '<div class="pagination-previous alignleft">%s</div>', $prev_link ) : '';
$pagination .= $next_link ? sprintf( '<div class="pagination-next alignright">%s</div>', $next_link ) : '';

echo $pagination:

}

Or

You could use the_posts_pagination()


WP_Query docs gives a warning about the offset parameter: Setting the offset parameter overrides/ignores the paged parameter and breaks pagination.

Try something like this:

 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $newsArticles = new WP_Query(array(
        'posts_per_page' => 16,
        'post_type'=> 'news',
        'paged' => $paged,
    ));
while(  $newsArticles->have_posts()){
        $newsArticles->the_post(); ?>

        // HTML

<?php } ?>


$big = 999999999; // need an unlikely integer
echo paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '?paged=%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $newsArticles->max_num_pages
) );

See more examples of paginate_links here:

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.