Pagination without plugin

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
<?php
function pagination($prev = '«', $next = '»') {
    global $wp_query, $wp_rewrite;
    $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
    $pagination = array(
        'base' => @add_query_arg('paged','%#%'),
        'format' => '',
        'total' => $wp_query->max_num_pages,
        'current' => $current,
        'prev_text' => __($prev),
        'next_text' => __($next),
        'type' => 'plain'
);
    if( $wp_rewrite->using_permalinks() )
        $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );

    if( !empty($wp_query->query_vars['s']) )
        $pagination['add_args'] = array( 's' => get_query_var( 's' ) );

    echo paginate_links( $pagination );
};
?>

Instructions:

This snippet creates a classic paging navigation like the one seen in WP-PageNavi, which give a better overview for the user. It’s easy to implement and gives you total control over the output. I’ll give you an example of how it can look:

[1] 2 3 ... 5 »
« 1 [2] 3 4 5 »
« 1 [2] 3 4 5 »
« 1 ... 3 4 [5]

To implement it, just add this code to functions.php:

Now you can add the pagination using the pagination(). function. Add it somewhere outside the loop, but inside the if( have_post() ) statement.

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
        // post goes here
    <?php endwhile; ?>

    <div class="pagination"><?php pagination('»', '«'); ?></div>

<?php endif; ?>

WordPress also gives you some CSS classes you can use to customize the look of the new navigation. See the example and you’ll figure out how to style it:

.page-numbers { font-size: 15px; }
.page-numbers.current { color: #222; }
.page-numbers .dots { letter-spacing: 1px }
a.page-numbers  { font-size: 14px; color: #3888ff; }

Share this snippet

If you like this snippet, share it with friends!