X

Pagination without plugin

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:

Code Snippet:

[1] 2 3 ... 5 »<br />
« 1 [2] 3 4 5 »<br />
« 1 [2] 3 4 5 »<br />
« 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.

Code Snippet:

<?php if ( have_posts() ) : ?><br />
    <?php while ( have_posts() ) : the_post(); ?><br />
        // post goes here<br />
    <?php endwhile; ?></p>
<p>    &lt;div class="pagination"><?php pagination('»', '«'); ?>&lt;/div></p>
<p><?php endif; ?><br />

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:

Code Snippet:

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

Code Snippet:

<?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 );
};
?>

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!