Ramaz Kadgaev
Ramaz Kadgaev

Reputation: 81

Custom WP_Query pagination shows 404 after page-2

Here is my index.php loop:

<?php 
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'posts_per_page' => 3, 'paged' => $paged ) ); 
?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
      <article>
        <h3><?php the_title(); ?></h3>
      </article>
<?php endwhile; ?>

<?php if ( get_next_posts_link('Next', $query->max_num_pages)) : ?>
  <nav class="navigation paging-navigation" role="navigation">
    <?php echo get_next_posts_link( 'Next', $query->max_num_pages ); ?>
  </nav>
<?php endif; ?>

  <?php wp_reset_postdata(); ?>

<?php else:  ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

It's pretty simple, but the problem is in pagination. On index page I have link to page/2 and when I click it everything looks fine, but while I am on page/2 and click link Next to get to page/3 I get 404 error.
What I am doing wrong?

Upvotes: 1

Views: 1504

Answers (2)

Ramaz Kadgaev
Ramaz Kadgaev

Reputation: 81

I have found a solution, it was not hard for index.php but then I noticed that my tag.php not showing even page/2, so I have made a bit changes there to make it working:

function my_post_count_queries( $query ) {
  if (!is_admin() && $query->is_main_query()){
    if(is_home()){ $query->set('posts_per_page', 1); }
    if(is_tag()){ 
        $query->set('post_type', array( 'product' ) );
        $query->set('posts_per_page', 1);
    }
  }
}
add_action( 'pre_get_posts', 'my_post_count_queries' );

Upvotes: 1

Aakanksh Patel
Aakanksh Patel

Reputation: 623

Please try to add this code in functions.php and check the pagination again

<?php
if ( ! function_exists('my_pagination')) :
    function my_pagination() {
        global $wp_query;

        $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' => $wp_query->max_num_pages
        ) );
    }
endif;

?>

And add this code before reset post meta

 <div class="blog_pagination">
         <?php my_pagination(); ?>
  </div>

Hope this work

Upvotes: 0

Related Questions