posts_per_page & pagination conflict

The question:

I have a custom query to display my custom post type. posts_per_page set to ‘5’. In admin post per page set to ’10’ (settings => Reading => Blog pages show at most 10 posts)
My template lists 5 posts per page. If I have 15 posts it must be shown in 3 pages, but on third page I get 404 error. So my pagination uses the admin settings (10 posts per page). How can I fix it?

global $paged;
query_posts(array(
    'post_type' => 'custom_post_type',
    'posts_per_page' => 5,
    'orderby' => 'title',
    'order' => 'ASC',
    'paged' => $paged
    ));

while (have_posts()) : the_post();
    the_title();
endwhile;

next_posts_link('Next');
previous_posts_link('Prev');

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Pagination is calculated before you get to the template file that runs query_posts. The proper way to alter posts_per_page conditionally is to use the pre_get_posts hook to modify the main query.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment