Advanced Post Pagination

WordPress comes out of the box with pagination built in. However, it has a tendency to display all pages. E.g. if you have a 1000 pages each page displaying 10 records it will output page 1 to 100. You don’t always want this, especially if you have a lot of pages. In this scenario you might only want to display the pages in chunks of 3 or 5 pages at the time. The following function does exactly that:

function my_pagination( $page_range = 3, $query = NULL )
{
   global $wp_query;

   if( empty( $query ) )
   {
      $query = $wp_query;
   }

   $page = $query->query_vars["paged"];

   if( !$page )
   {
      $page = 1;
   }

   $page_start = floor( ($page - 1) / $page_range) * $page_range + 1;
   $page_end = $page_start + $page_range - 1;

   if( $page_end > $query->max_num_pages )
   {
      $page_end = $query->max_num_pages;
   }

   echo '<ol>';

   if( $page > 1 )
   {
      echo '<li><a href="'.previous_posts(FALSE).'" rel="prev">Previous</a></li>';
   }

   for( $i = $page_start; $i <= $page_end; $i++ )
   {
      $selected = "";

      if( $page == $i)
      {
         $selected = " class=\"selected\"";
      }

      $url = get_pagenum_link( $i );

      echo "<li$selected><a href=\"$url\">$i</a></li>";
   }

   if( $page < $query->max_num_pages )
   {
      echo '<li><a href="'.next_posts($query->max_num_pages, FALSE).'" rel="next">Next</a></li>';
   }

   echo '</ol>';
}

Bon App├ętit!

Tagged with: