You will notice that there are WordPress websites that uses next and previous links as pagination while there are others that uses numeric pagination.

Well, it depends upon the content that you want to deliver. If you are showing blog posts or articles, the next and previous links will be good to go. However, if you are showing items like files for example, a numeric pagination might be a good choice.

Today I will show you how to add a numeric pagination in a WordPress query.

To start with, paste the function below into your theme’s functions.php.

function wp_numeric_pagination() {
    global $wp_query;

    $big = 999999999;
    $tag = '<div class="pagination">' . PHP_EOL;
    $tag .= paginate_links( array(
            'base'              => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format'            => '?paged=%#%',
            'current'           => max( 1, get_query_var('paged') ),
            'total'             => $wp_query->max_num_pages,
            'prev_next'         => True,
            'prev_text'         => __('«'),
            'next_text'         => __('»'),
        ) ) . PHP_EOL;

    $tag .= '</div>' . PHP_EOL;
    echo $tag;
}

Simply call the function after the loop where you want to display a numeric pagination.

Usage Example

Now let’s create a new template file and paste the code below.

<?php
/**
 * Template Name: Music Template
 */

$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
    'post_type' => 'music',
    'posts_per_page' => 10,
    'paged' => $paged
);
$wp_query = new WP_Query( $args );

if( $wp_query->have_posts() ) :
    ?>
    <ul>
        <?php 
        //the loop
        while( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

            <li>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            </li>

        <?php endwhile; wp_reset_postdata(); ?>
    </ul>

    <?php wp_numeric_pagination(); ?>

<?php else : ?>

    <h3>OPPPS! No content found.</h3>

<?php endif; ?>

In our example above, we created a new instance of WP_Query.

We added the paged parameter into the arguments to get the pagination number of the current page.

Using posts_per_page, we specify how many items we are going to display in a page.

After the loop, we called the wp_numeric_pagination() function to display the pagination links.

Please note we use the global $wp_query variable within the wp_numeric_pagination function so make sure to use that when creating new instance of WP_Query otherwise, the pagination will not work. Example $wp_query = new WP_Query()