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');
link|improve this question

75% accept rate
feedback

1 Answer

up vote 0 down vote accepted

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.

link|improve this answer
Thank you for your answer. I googled a lot and I realized my concept is absolutely wrong. My code above is part of a taxonomiy-$taxonomiy-$term.php file which has a main query. query_posts(); is for altering main query in custom templates. So I delete query_posts(); and have to modify my main query with a hook, am I right? :) I tried to hook with pre_get_posts but couldn't managed. Could you please show me an example? thanks – user9909 Feb 13 at 14:58
Ok, now everithing works great. I deleted the whole query_posts from template file, and put a pre_get_posts hook into functions.php thank you for your help you drove me to the right way. ;) – user9909 Feb 14 at 12:21
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.