Skip to content

Instantly share code, notes, and snippets.

@croosen
Created September 26, 2017 08:04
Show Gist options
  • Save croosen/0ae584255a776882489ce3cd48f7b74e to your computer and use it in GitHub Desktop.
Save croosen/0ae584255a776882489ce3cd48f7b74e to your computer and use it in GitHub Desktop.
PHP pagination
// A PHP pagination, based on this tutorial: https://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928
// Adjusted for own use, fixed some bugs (prev/next links did not stop counting after first or last page was reached)
function pagination($page, $total, $limit, $url)
{
$links = 1; // links to show next to the current link, e.g. 1 = 3 links max.
$list_class = "paginate"; // classname for the pagination list
$limit = $limit ? $limit : 10; // posts per page
$page = $page ? $page : 1; // currentpage
$total = $total; // total amount of posts
$last = ceil( $total / $limit );
$start = ( ( $page - $links ) > 0 ) ? $page - $links : 1;
$end = ( ( $page + $links ) < $last ) ? $page + $links : $last;
$html = '<ul class="' . $list_class . '">';
$html .= '<li><a href="' . $url . '1"><i class="fa fa-angle-double-left"></i></a></li>';
$class = ( $page == 1 ) ? "disabled" : "";
$html .= '<li class="' . $class . '"><a href="' . $url . '' . ( ( $page != 1 ) ? $page - 1 : 1 ) . '"><i class="fa fa-angle-left"></i></a></li>';
if ( $start > 1 ) {
$html .= '<li><a href="' . $url . '1">1</a></li>';
$html .= '<li class="disabled dots"><span>...</span></li>';
}
for ( $i = $start ; $i <= $end; $i++ ) {
$class = ( $page == $i ) ? "active" : "";
$html .= '<li class="' . $class . '"><a href="' . $url . '' . $i . '">' . $i . '</a></li>';
}
if ( $end < $last ) {
$html .= '<li class="disabled dots"><span>...</span></li>';
$html .= '<li><a href="' . $url . '' . $last . '">' . $last . '</a></li>';
}
$class = ( $page == $last ) ? "disabled" : "";
$html .= '<li class="' . $class . '"><a href="' . $url . '' . ( ( $page != $last ) ? $page + 1 : $last ) . '"><i class="fa fa-angle-right"></i></a></li>';
$html .= '<li><a href="' . $url . '' . $last . '"><i class="fa fa-angle-double-right"></i></a></li>';
$html .= '</ul>';
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment