Pagination with WP_Query is buggy – working for some pages, but not the others

WordPress does its own query on every page. You should modify that query instead of creating a new one. What happens now is that WordPress does a query with the standard posts per page of 10, but you don’t do anything with these results and do your own query. This works… until WordPress goes beyond post #33, which is on page number 4.

  1. WordPress queries 1-10, your template queries 1-4
  2. WordPress queries 11-20, your template queries 5-8
  3. WordPress queries 21-30, your template queries 9-12
  4. WordPress queries 31-40, your template queries 13-16
  5. WordPress queries 41-50, but gets no results, so it gives 404. Your template doesn’t load.

So instead you should modify the standard query that WordPress will execute, by placing this in your functions.php or in a plugin:

add_action( 'pre_get_posts', 'wpse7687_pre_get_posts' );
function wpse7687_pre_get_posts( &$wp_query ) {
    if ( $wp_query->is_category && 'latest-news' == $wp_query->get_queried_object()->slug ) {
        $wp_query->set( 'posts_per_page', 4 );
    }
}

Leave a Comment