How to add custom pagination to WP Query

Screen Shot 2016-04-24 at 11.23.49

Summary

WordPress by default only provides a previous and next post link. However, for some of my designs I require paginated numbers and a line which says what page the user is on.

Solution:

  1. Add the following to your functions.php:

    function custom_pagination($numpages = '', $pagerange = '', $paged='') {
    
    if (empty($pagerange)) {
       $pagerange = 2;
    }
    
    /**
    * This first part of our function is a fallback
    * for custom pagination inside a regular loop that
    * uses the global $paged and global $wp_query variables.
    *
    * It's good because we can now override default pagination
    * in our theme, and use this function in default quries
    * and custom queries.
    */
    global $paged;
    if (empty($paged)) {
      $paged = 1;
    }
    if ($numpages == '') {
       global $wp_query;
       $numpages = $wp_query->max_num_pages;
       if(!$numpages) {
           $numpages = 1;
       }
    }
    
    /**
    * We construct the pagination arguments to enter into our paginate_links
    * function.
    */
    $pagination_args = array(
       'base' => get_pagenum_link(1) . '%_%',
       'format' => 'page/%#%',
       'total' => $numpages,
       'current' => $paged,
       'show_all' => False,
       'end_size' => 1,
       'mid_size' => $pagerange,
       'prev_next' => True,
       'prev_text' => __('«'),
       'next_text' => __('»'),
       'type' => 'plain',
       'add_args' => false,
       'add_fragment' => ''
    );
    
    $paginate_links = paginate_links($pagination_args);
    
    if ($paginate_links) {
       echo "<nav class='custom-pagination clearfix'>";
       echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
       echo $paginate_links;
       echo "</nav>";
    }
    
    } // end function
  2. And finally you can add this to your theme page where you would like the pagination to show.
    Note: Change $loop to your variable

    if (function_exists('custom_pagination')) {
       custom_pagination($loop->max_num_pages,"",$paged);
    }
  3. This will output the following HTML so you can use CSS to style.

    <nav class="custom-pagination">
      <span class="page-numbers page-num">Page 1 of 3</span><br> <span class="page-numbers current">1</span>
      <a class="page-numbers" href="http://www.bookaid.org/latest/page/2">2</a>
      <a class="page-numbers" href="http://www.bookaid.org/latest/page/3">3</a>
      <a class="next page-numbers" href="http://www.bookaid.org/latest/page/2">ยป</a>
    </nav>