Limit WordPress Pagination

Please note that the information in this post may no longer be accurate or up to date. I recommend checking more recent posts or official documentation for the most current information on this topic. This post has not been updated and is being kept for archival purposes.

I ran into a pickle the other day where I had to display the latest posts in WordPress and limit the number of pages created by the wp_pagenavi plugin. On a site with thousands of posts, the plugin was returning 400+ pages. Obviously, we only wanted to show up to around 4-pages of data.

How to Limit the Number of Pages Output by wp_pagenavi

The plugin uses the max_num_pages variable to figure the number of pages it should paginate. You have to manually set this variable if you want to limit pagination. Here’s a bit of code that will do that:

Place this after your query:

//limit the number of pages
$the_query->max_num_pages = 4

Example of WP_Query() and Limit Pagination

 $paged,
        'showposts' => 50
    ); 
//get the data using WP_Query the function
$the_query = new WP_Query( $args );
//limit the number of pages
$the_query->max_num_pages = 4;

    if (have_posts()) :  while ($the_query->have_posts()) : $the_query->the_post();

    //output your data here such as the_title(), the_content(), etc.

    endwhile; endif;

    //using wp_pagenavi and tell it to use our custom query
    if(function_exists('wp_pagenavi')) {
            wp_pagenavi(
                array(
                     'query' =>$the_query
                )
            );
        }

Once you set the max_num_pages to whatever you wish, you will now see the number of pages returned by the plugin to your new number.

Remember to Check the WP-PageNavi Options

WP_PageNavi has an option panel in the backend to limit the number of pages shown. This may work for you, however, keep in mind that for my situation it wouldn’t because the “Last” link would take the user to page 400+ since it’s using the max_num_pages.

Hope this helps!

Similar Posts