Snippet: pageLinks
March 10, 2009
I always hated all the various pagination templates that use full on classes or multiple pages to create a few links. All I needed was a simple function that would do the bare minimum and could easily be manipulated. Here's a little something I created for my own libraries, and hopefully you can find some use of it.
$max_links should be an even number, but the function will add 1 to an odd number. It will also add the page numbers in the form of page=# to the end of your $href variable, so keep that in mind.
/**
* pageLinks() - returns a list of links in order
* Corey Hart @ http://www.codenothing.com
* March 10, 2009
*
* $href: Full link of the current page without the 'page' var
* $current_page: Current page #
* $total_entries: Total number of entries
* $entries_per_page: Maximum entries per page
* $max_links: Maximum links on display
*/
function pageLinks($href, $current_page, $total_entries, $entries_per_page, $max_links=8){
// Maximum links on display must always start even
$max_links = ($max_links % 2 == 0) ? $max_links : $max_links+1;
// Highest page number
$highest_page = intval(($total_entries/$entries_per_page)+.99);
// Set the start of the page number
if ($current_page - ($max_links/2) < 0){
$page = 0;
}else if ($current_page + ($max_links/2) > $highest_page-1){
$page = $highest_page - $max_links;
if ($page < 0) $page = 0;
}else{
$page = $current_page - ($max_links/2);
}
// Loop through and set the page links
for ($i=0; $i<($max_links+1); $i++){
// Last link to be returned
if ($i == $max_links || $page == $highest_page-1 || $total_entries <= $entries_per_page){
// Check to see if page is currently being viewed
$list .= ($current_page == $page) ? "<b>$page</b>" : "<a href='$href&page=$page'>$page</a>";
break;
}
else{
// Check to see if page is currently being viewed
$list .= ($current_page == $page) ? "<b>$page</b>," : "<a href='$href&page=$page'>$page</a>,";
}
$page++;
}
return $list;
}
RSS