When developing WordPress themes, the built-in post pagination may not always meet specific design requirements. In such cases, a custom pagination navigation is needed. This article demonstrates how to create a pagination style that combines 'Previous/Next' links with numbered page links, without relying on plugins.
Core Function Code
function custom_pagination() {
global $wp_query;
$big = 999999999;
$args = 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,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'type' => 'plain'
);
echo paginate_links( $args );
}
Code Explanation
- base: The base URL structure used to build pagination links.
- format: The URL format for page numbers;
%#%is replaced by the page number. - current: Gets the current page number, ensuring a minimum of 1.
- total: Total number of pages, typically from the main query.
- mid_size: Controls how many page numbers appear on each side of the current page (e.g., 2 produces « Previous ... 3 4 [5] 6 7 ... Next »).
- prev_text / next_text: Custom text for the 'Previous' and 'Next' links.
How to Use
Add the custom_pagination function to your theme's functions.php file. Then, call it in the template file where you want the pagination to appear (e.g., index.php, archive.php, or search.php):
<?php custom_pagination(); ?>
Important Notes
- Call this function after the main loop (
if ( have_posts() ) : while ( have_posts() ) : the_post();). - This function relies on WordPress's core
paginate_links()function, ensuring good compatibility. - To adjust styling, use CSS to target the classes output by the pagination links.