CUTCODEDOWN
Minimalist Semantic Markup

Welcome Guest
Please Login or Register

If you have registered but not recieved your activation e-mail in a reasonable amount of time, please use our Contact Form for assistance. Include both your username and the e-mail you tried to register with.

Author Topic: PHP - pagination  (Read 18 times)

Jason Knight

  • Administrator
  • Sr. Member
  • *****
  • Posts: 275
  • Karma: +25/-0
    • View Profile
    • CutCodeDown -- Minimalist Semantic Markup
PHP - pagination
« on: 10 Feb 2020, 09:37:16 am »
Just thought I'd share my pagination routine as on several forums I've seen people struggling with this.

Code: [Select]
function template_pagination($urlRoot, $current, $perPage, $totalArticles) {

if ($totalArticles > $perPage) { // don't bother if only one page

echo '
<div class="pagination">
Pages:
<ul>';

if (($currentPage = floor($current / $perPage)) > 0) echo '
<li><a href="', $urlRoot, '0">First</a></li>
<li><a href="', $urlRoot, $currentPage - 1, '" title="previous" rel="previous">&laquo;</a></li>';

if (($lastPage = floor(($totalArticles - 1) / $perPage)) > 9) {
$counter = ($currentPage < 6) ? 0 : $currentPage - 5;
if (($endPage = $counter + 10) > $lastPage) {
$endPage = $lastPage;
$counter = $endPage - 10;
}
} else {
$counter = 0;
$endPage = $lastPage;
}

while ($counter <= $endPage) {
echo '
<li>', (
($noAnchor = ($counter == $currentPage)) ?
'<span>' :
'<a href="' . $urlRoot . $counter . '">'
), ++$counter, (
$noAnchor ?
'</span>' :
'</a>'
), '</li>';
}

if ($currentPage < $lastPage) echo '
<li><a href="', $urlRoot, ++$currentPage, '" title="next" rel="next">&raquo;</a></li>
<li><a href="', $urlRoot, $lastPage, '">Last</a></li>';

echo '
</ul>
<!-- .pagination --></div>';

}

} // template_pagination

It shows a first link, previous link, 5 before the current page, 5 after the current page, next link, and last link. The first/previous links are omitted if on the first page, the next and last links are similarly omitted if on the last page. If within the last 5 links the number before the current page is increased, and vice versa if within the first five pages.

... and more than enough hooks are present to style it however you like. I suggest setting the LI to display:inline, the anchors and span to inline block so you can pad the top and bottom of them, as then alignment is a simple matter of text-align.

Example use:

Code: [Select]
template_pagination('blogs/list?page=', 3, 10, 63);
Where you want the href to read something like "blogs/list?page=4" for the next page, you're currently on page 3, you want ten articles/sections per page, and there are 63 articles in total on the site. It handles all the rest of the math for you.
"It is amazing what can be accomplished when nobody cares who gets the credit." -- Kelly Johnson

 

Advertisement