Adding pagination in WordPress is easy by just adding next and previous buttons using WordPress Pagination but how can we add numeric pagination in loop?
First we need to create a function for custom numeric pagination inside a regular loop. This function has a global paged and wp_query variables. Also we will use the paginate_links function in WordPress
function hdev_custom_numeric_pagination( $number_pages = '', $page_range = '', $paged = '') { if (empty($page_range)) { $page_range = 2; } global $paged; if (empty($paged)) { $paged = 1; } if ($number_pages == '') { global $wp_query; $number_pages = $wp_query->max_num_pages; if (!$number_pages) { $number_pages = 1; } } $pagination_args = array( 'base' => get_pagenum_link(1) . '%_%', 'format' => 'page/%#%', 'total' => $number_pages, 'current' => $paged, 'show_all' => false, 'end_size' => 1, 'mid_size' => $page_range, 'prev_next' => true, 'prev_text' => __('«'), 'next_text' => __('»'), 'type' => 'plain', 'add_args' => false, 'add_fragment' => '' ); $paginate_links = paginate_links($pagination_args); if ($paginate_links) { echo '<div class="hdev-pagination-wrap">'; echo "<nav class='hdev-custom-pagination'>"; echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $number_pages . "</span> "; echo $paginate_links; echo "</nav>"; echo '</div>'; } }
You can now add the function on your Loop
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => 'post', 'posts_per_page' => 8, 'paged' => $paged, 'order' => 'DESC', 'orderby' => 'date' ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); echo get_the_title().'<br />'; endwhile; hdev_custom_numeric_pagination($the_query->max_num_pages, "", $paged); endif; wp_reset_postdata();