Skip to content

Instantly share code, notes, and snippets.

@galen
Created March 14, 2013 01:39
Show Gist options
  • Save galen/5158135 to your computer and use it in GitHub Desktop.
Save galen/5158135 to your computer and use it in GitHub Desktop.
Given the current page, total pages, and viewport this function returns an object with all the info needed to create pagination.
function get_pagination( $current_page, $total_pages, $pagination_viewport ) {
$start_page = max( $current_page - $pagination_viewport, 1 );
$end_page = min( $start_page + ( $pagination_viewport * 2 ), $total_pages );
$start_page = max( $end_page - ( $pagination_viewport * 2 ), 1 );
$pages = range( $start_page, $end_page );
$first_page_link = $last_page_link = false;
if ( !in_array( 1, $pages ) ) {
$first_page_link = true;
}
if ( !in_array( $total_pages, $pages ) ) {
$last_page_link = true;
}
$previous_page = $current_page == 1 ? null : $current_page - 1;
$next_page = $current_page == $total_pages ? null : $current_page + 1;
return (object) array(
'current_page' => $current_page,
'pages' => $pages,
'previous_page' => $previous_page,
'next_page' => $next_page,
'total_pages' => $total_pages,
'first_page_link' => $first_page_link,
'last_page_link' => $last_page_link
);
}
<?php if( $pagination->total_pages > 1 ): ?>
<ul class="pagination">
<?php if( $pagination->first_page_link ): ?><li class="first-page-warp"><a href="?page=1">1...</a></li><?php endif; ?>
<?php if( $pagination->previous_page ): ?><li class="prev-page"><a href="?page=<?= $pagination->previous_page ?>">&larr;</a></li><?php endif; ?>
<?php foreach( $pagination->pages as $page ): ?>
<?php if( $page == $pagination->current_page ): ?><li class="current-page"><?= $page ?></li><?php else: ?><li><a href="?page=<?= $page ?>"><?= $page ?></a></li><?php endif; ?>
<?php endforeach; ?>
<?php if( $pagination->next_page ): ?><li class="next-page"><a href="?page=<?= $pagination->next_page ?>">&rarr;</a></li><?php endif; ?>
<?php if( $pagination->last_page_link ): ?><li class="last-page-warp"><a href="?page=<?= $pagination->total_pages ?>">...<?= $pagination->total_pages ?></a></li><?php endif; ?>
</ul>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment