WordPress Pagination not displaying posts after certain page

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:

Read More
$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?

Related posts

Leave a Reply

1 comment

  1. 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.