Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm having an issue with pagination. I have a media category, using a category-media.php template. I have a custom loop with a paged variable. There are 30 posts total.

Sample:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
   'posts_per_page'   =>  3,
   'category_name' =>  'media',
   'paged' => $paged
);

$my_loop = new WP_Query( $args );

echo $my_loop->max_num_pages . "<br><br>";

while ($my_loop->have_posts()) : $my_loop->the_post();

  echo get_the_title() . "<br><br><br>";

endwhile;

wp_pagenavi( array( 'query' => $my_loop ) );

Pagination shows up fine and max_num_pages even echos out 10 pages. When I start clicking through the pagination links, nothing shows for pages past page 5. My reading setting are set at 6 per page. If I comment out the posts_per_page parameter, pagination works fine.

I feel like it's something simple that I'm overlooking. Any ideas?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

WordPress determines if a paginated page exists based on the results of the main query. Each page is actually querying 6 posts, while your custom query only loads 3.

The solution - Don't create a new query in the template, use pre_get_posts to modify the main query via your theme's functions.php

function wpa90437_media_category( $query ) {
    if ( $query->is_category('media') && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 3 );
    }
}
add_action( 'pre_get_posts', 'wpa90437_media_category' );

Then just run the normal loop in your template.

share|improve this answer
    
Worked perfectly. Thank you for taking the time to explain it. Do you know where I can find more info on parameters such as $query->is_main_query()? –  certainstrings Mar 12 '13 at 3:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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