Pagination - Show Min/Max Page Numbers

2 posts by 2 authors in: Forums > CMS Builder
Last Post: July 17, 2014   (RSS)

By Perchpole - July 17, 2014

Hello, All

I'm using a standard bit of code on my product list pages to show the pagination numbers:

<?php   
  if (@!$_GET['page']): $current_page = "1";  
  else: $current_page = $_GET['page'];     
  endif; 
?>
    
<?php  
  $startNumber = max($current_page - 6, 1);  
  $endNumber   = min($current_page + 6, $productsMetaData['totalPages']);  
?>
    
<?php foreach (range($startNumber,$endNumber) as $paginate): ?>
  <?php if ($paginate == $current_page): ?>
    <li class="current"><a href="#"><?php echo $paginate; ?></a></li>
  <?php else: ?>
    <li><a href="<?php echo $settings['indexPage'] ?>?p=<?php echo $selectedPage['num'] ?>&page=<?php echo $paginate; ?>"><?php echo $paginate; ?></a></li>
  <?php endif ?>
<?php endforeach; ?>

Currently the code is set up to show the numbers 6 places either side of the selected page. So, if you are on page 7 you'd see this:

1 2 3 4 5 6 7 8 9 10 11 12 13

If you go to page 12, you'd get this:

6 7 8 9 10 11 12 13 14 15 16 17 18

It works fine but I'd like to stretch it a little by replacing the numbers on either end of the range with the first and last page numbers. So (using the example above) it would result in something like this:

1... 7 8 9 10 11 12 13 14 15 16 17 ...24

If the first and last numbers aren't visible in the sequence, the script adds them to either end as required. It looks much better and informs the visitor exactly how many pages there are in the range.

Do-able?

Perch

By claire - July 17, 2014

Hey Perch

You've already got the total pages there - $productsMetaData['totalPages']. That's your final number. Just add this to your code:

<?php echo $startNumber < 7 ? '' : '<li><a href="'.$settings['indexPage'].'?p='.$selectedPage['num'].'">1</a>...</li>'; ?>
<?php foreach (range($startNumber,$endNumber) as $paginate): ?>
  <?php if ($paginate == $current_page): ?>
    <li class="current"><a href="#"><?php echo $paginate; ?></a></li>
  <?php else: ?>
    <li><a href="<?php echo $settings['indexPage'] ?>?p=<?php echo $selectedPage['num'] ?>&page=<?php echo $paginate; ?>"><?php echo $paginate; ?></a></li>
  <?php endif ?>
<?php endforeach; ?>
<?php echo $endNumber < $current_page + 7 ? '' : '<li>...<a href="'.$settings['indexPage'].'?p='.$selectedPage['num'].'&page='.$endNumber.'">'.$endNumber.'</a></li>'; ?>

I think that should do it. Let me know if it works.

--------------------

Claire Ryan
interactivetools.com

Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/