0
votes

I'm using a simple loop with query_posts on my category template, with a custom function for pagination. First page works great, but when I to reach next page (/page/2) using the next button, I get a 404 error.

In my category.php :

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array ( 'category' => ID, 'posts_per_page' => 6, 'paged' => $paged);
$myposts = query_posts( $args );
if(have_posts()) :
      foreach( $myposts as $post ) :    setup_postdata($post);
      ?>    
      <article>
      ...
      </article>
      <?php
      endforeach;
else :
      echo '<p class="intro-contact">' . _e( 'No news available', 'cja_theme' ) . '</p>';
endif;
cja_numeric_posts_nav();
?>

.htaccess :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /public/www.mywebsite.com/

RewriteRule ^la-residence/$ la-residence/qui-sommes-nous/ [L,R=301]
RewriteRule ^informations/$ informations/acces-a-la-residence/ [L,R=301]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /public/www.mywebsite.com/index.php [L]
</IfModule>

Generated URL is correct, and in the Back Office the max posts per page option is set to 6 too. I tried to use that fix in my functions.php file but it didn't help :

function cja_fix_pagination($query_string)
{
  if(!is_home())
    $query_string['posts_per_page'] = 6;
  return $query_string;
}
add_filter('request', 'cja_fix_pagination');
1
That is exactly why you should never ever use query_posts and also why you should never use a custom query to replace the main query on any type of archive page - Pieter Goosen

1 Answers

1
votes

That is exactly why you should never ever use query_posts and also why you should never use a custom query to replace the main query on any type of archive page

To solve your issue, return to the default loop as it should be

if(have_posts()) {
   while(have_posts()) {
     the_post();

       //YOUR LOOP ELEMENTS

    }
}

Then, in your functions.php, use pre_get_posts to alter the main query accordingly

function ppp_category( $query ) {
    if ( !is_admin && $query->is_category() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', '6' );
    }
}
add_action( 'pre_get_posts', 'ppp_category' );