A second page contain content from a first page

Problem: We have the bug – second pagination page contain content from first page.

Pagination bug — a second page contain content from a first page

Solution: For pagination was used next code:

<?php
$args = [
	'post_type' => $post_type,
	'posts_per_page' => $posts_per_page,
	'order' => 'DESC',
	'orderby' => 'date',
];

$query = new WP_Query( $args );

$total_pages = $query->max_num_pages;

if ( $query->have_posts() ) : 

	while ( $query->have_posts() ) : $query->the_post();
...
	endwhile;

	if ( $total_pages > 1 ) : ?>
		<div class="pagination">
		<?php $current_page = max( 1, get_query_var( 'paged' ) );
			echo paginate_links( [
			'base' => get_pagenum_link( 1 ) . '%_%',
			'format' => 'page/%#%',
			'current' => $current_page,
			'total' => $total_pages,
			'prev_text' => __( '' ),
			'next_text' => __( '' ),
			] ); ?>
		</div>
	<?php endif; 
	wp_reset_postdata();
endif; ?>

It's all about in absence magic string:

$paged = get_query_var('paged') ? get_query_var('paged') : 1;

The string should be write before array of arguments $args and next add this argument 'paged' => $paged, to array $args. Look it:

<?php
$paged = get_query_var('paged') ? get_query_var('paged') : 1;

$args = [
	'post_type' => $post_type,
	'posts_per_page' => $posts_per_page,
    'paged' => $paged,
	'order' => 'DESC',
	'orderby' => 'date',
]; 

#UPD 24/04/20: Note! If we need pagination on the Static Page (e.g. Home) we need use get_query_var( 'page' ) instead get_query_var( 'paged' ).

Source:

  1. https://wordpress.stackexchange.com/questions/185075/wp-query-and-pagination-on-a-static-front-page

Leave Comment

Your email address will not be published. Required fields are marked *