[WordPress] Pagination Without a Plugin

11 November, 2016

[WordPress] Pagination Without a Plugin

I really hate using plugins, whenever I can I try to use my own code, or code that a found on the internet for something specific.

There is some nice plugins to show post pagination on your WordPress site, like the famous WP-PageNavi, but they aren’t really necessary if you only want to add a simple navigation. Here’s how you can do it…

First you create a function on your functions.php file, this function will check for how many pages there is and display the number. You can chose how many numbers to show, in this example we are only going to show 5 pages, the current one and the next 2 anos and the past two one, plus the next and previous buttons. You can change how much you want to show by changing the number “2” in the code.

/** Pagination */
function pl_pagination($pages = '', $range = 2) {
$showitems = ($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 "<ul class=\"pagination pagination-lg\">\n";
if($paged > 1 && $showitems < $pages) echo "<li><a href=\"".get_pagenum_link($paged - 1)."\">&laquo;</a></li>\n";

for ($i=1; $i <= $pages; $i++) {
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )) {
echo ($paged == $i)? "<li class=\"active\"><a href=\"".get_pagenum_link($i)."\">" .$i. "</a></li>\n":"<li><a href=\"".get_pagenum_link($i)."\">" .$i. "</a></li>\n";
if ($paged < $pages && $showitems < $pages) echo "<li><a href=\"".get_pagenum_link($paged + 1)."\">&raquo;</a></li>\n";
echo "</ul>\n";

Next, you need to add this next code after a WordPress query, where you want to show the pagination.

<?php if(function_exists('pl_pagination') && isset($pages)) { ?>
<div id="paginacao">
<div class="pagination-centered">
<?php pl_pagination(); ?>
<?php } ?>

And that’s it! Now you have your own pagination! You can style it using CSS, but in this case I’m using bootstrap classes, so, there’s no need to add CSS.

Leave a Comment