Skip to content

Instantly share code, notes, and snippets.

@i-like-robots
Created August 22, 2012 09:46
Show Gist options
  • Save i-like-robots/3424071 to your computer and use it in GitHub Desktop.
Save i-like-robots/3424071 to your computer and use it in GitHub Desktop.
Wordpress pagination
/**
* Archive pagination
* @param string $prevText Previous page link text. Leave blank to ignore.
* @param string $nextText Next page link text. Leave blank to ignore.
* @param integer $break Number of page links to display before truncation. Set to 0 to ignore.
*/
public static function archive_pagination($prevText = 'Previous', $nextText = 'Next', $break = 10)
{
// Maximum pages
global $wp_query;
$pages = (int) $wp_query->max_num_pages; // This can return floating points =S
// Current page (returns 0 if undefined)
$current = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
// Calculate if pagination requires truncating
$pages_start = 1;
$pages_end = $pages;
$abbv_end = false;
$abbv_begin = false;
if ( $break && $pages > $break )
{
$split = ceil($break / 2);
// Lower boundary break (1,2,3,4,5,6,7,8,9,10...)
if ( $current < $split )
{
$pages_end = $break;
$abbv_end = true;
}
// Middle boundary break (...5,6,7,8,9,10,11,12,13,14,15...)
else if ( $current >= $split && $current < ($pages - $split) )
{
$pages_start = $current - $split;
$pages_end = $current + $split;
$abbv_begin = $abbv_end = true;
}
// End boundary break (...10,11,12,13,14,15,16,17,18,19,20)
else if ( $current >= ($pages - $split) )
{
$pages_start = $pages - $break;
$abbv_begin = true;
}
}
// Print previous link
if ( $current > 1 && strlen($prevText) )
{
echo '<li><a href="' , get_pagenum_link($current - 1) , '" rel="prev">' , $prevText , "</a></li>\n";
}
// Print ellipsis
if ( $abbv_begin )
{
echo '<li>&hellip;</li>';
}
// Print page numbers
for ($i = $pages_start; $i <= $pages_end; $i++)
{
$selected = $current == $i ? ' class="selected"' : '';
echo '<li' , $selected , '><a href="' , get_pagenum_link($i) , '">' , $i , "</a></li>\n";
}
// Print ellipsis
if ( $abbv_end )
{
echo '<li>&hellip;</li>';
}
// Print next link
if ( $current < $pages && strlen($nextText) )
{
echo '<li><a href="' , get_pagenum_link($current + 1) , '" rel="next">' , $nextText , "</a></li>\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment