WordPress: paginating posts without plugins

I don't use a plugin such as WP-PageNavi to paginate my posts, but a simple custom function that I'd like to share with you. Let's see the details.

The custom function is as follows:

function create_pagination($pages = '', $range = 2) {

	$show_items = ($range * 2) + 1;
	global $paged;
	
	if(empty($paged)) { 
		$paged = 1;
	}
	
	if($pages == '') {
	
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         
         if(!$pages) {
             $pages = 1;
         }
     } 
     
     
     if(1 != $pages) {
         echo '<div id="pagination">';
         echo '<span class="pagination-where">Page ' . $paged . ' of ' . $pages . '</span> ';
         if($paged > 2 && $paged > $range+1 && $show_items < $pages) echo "<a href='".get_pagenum_link(1)."'>«</a>";
         if($paged > 1 && $show_items < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? '<strong>'.$i."</strong>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
             }
         }

         if ($paged < $pages && $show_items < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";  
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $show_items < $pages) echo "<a href='".get_pagenum_link($pages)."'>»</a>";
         echo "</div>\n";
     }
  

	


}

And here are the custom CSS styles:

#pagination { 
	margin: 0; 
	text-align: center;
	clear: both;
	width: 100%;
	font-family: Georgia, serif;
}
#pagination a:link,
#pagination a:visited,
#pagination strong { 
	display: inline-block; 
	text-decoration: none;  
	width: 32px;
	height: 32px;
	text-align: center;
	line-height: 32px;
	border: 1px solid #ccc;
	-moz-transition: all 500ms ease-in;
	-webkit-transition: all 500ms ease-in;
	-o-transition: all 500ms ease-in;
	-ms-transition: all 500ms ease-in;
	transition: all 500ms ease-in;
}
#pagination a:link, 
#pagination a:visited, 
#pagination strong { 
	margin-right: 0.5em;
}

#pagination a:link,
#pagination a:visited {
	color: #000;
}

#pagination strong, 
#pagination a:hover { 
	background: #ccc;
	color: #444; 
}

#pagination .pagination-where {
	display: block;
	height: 32px;
	line-height: 32px;
	text-align: center;
	margin-bottom: 0.5em;
}

You can use this function in your theme as follows:

<!-- end of the Loop -->
<?php create_pagination(); ?>

I hope you find it useful.

Back to top