Advanced Pagination For Custom Archives In WordPress

The Problem of Default Pagination on Archives

The default WordPress pagination for archive pages like category, tag, author, or date archives often does not meet the needs of site owners and readers. Issues with the built-in pagination include:

  • Only showing the next/previous links, with no page numbers
  • Not matching the visual style of the site
  • Lacking options to control number of posts per page
  • Poor performance with long archive lists
  • Confusion for readers when clicking between pages

Fortunately, the WordPress template hierarchy allows developers to override the default pagination through custom functions. By taping into hooks like preprocess_comment_query and customize the $wp_query, we can fully control archive pagination.

Understanding WordPress Pagination Functions

The main WordPress function that handles splitting post content into multiple pages is paginate_links(). This works together with $wp_query to divide the page content.

Key things the paginate_links() function does:

  • Accepts the query data from $wp_query to determine page info
  • Generates the numeric page links and previous/next links
  • Allows setting of query parameters like total pages and items per page
  • Outputs the HTML formatted page links

By tapping into paginate_links(), we can customize the pagination data and markup. Some handy filters to use are:

  • paginate_links
  • next_posts_link_attributes
  • previous_posts_link_attributes

These allow modifying the link text, URLs, CSS classes and more. The navigation functions next_posts_link() and previous_posts_link() also generate those directional links.

Creating a Custom Pagination Function

A custom pagination function wraps all the logic to query posts, calculate pages, generate markup, and apply filters in one place. The function will:

  1. Set the query variables like paged and posts_per_page
  2. Hook preprocess_comment_query to modify the main query
  3. Call paginate_links() to generate the page links
  4. Output formatted pagination HTML

Benefits of a custom function:

  • Reuse the same pagination on any archive
  • Easily set posts per page, link text, CSS classes
  • Localize all code to one file
  • Improved performance with optimized queries

The function can go in functions.php, or its own pagination.php file included in functions.php. Applying to archives is done through hooks like pre_get_posts.

Pagination Function Code Examples

A simple custom pagination function could look like:

function my_custom_pagination() {

  $args = [
    'total' => $wp_query->max_num_pages,
    'current' => max( 1, get_query_var('paged') ),
    'show_all' => false,
    'prev_next' => true,
    'prev_text' => __('Previous'),
    'next_text' => __('Next'),
  ];

  echo paginate_links($args);

}

A more advanced example handles post query modification, number of pages, formats the output, and applies filters:

function advanced_pagination() {

    global $wp_query; 

    $big = 999999999; 
  
    $pages = paginate_links( [
        '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_text' => 'Newer',
        'next_text' => 'Older',
    ] );

    $pagination = '';
    
    echo apply_filters('my_pagination', $pagination);

}

The key differences here are modification of the query, custom prev/next text, Added HTML wrappers, and apply filters to override markup. This makes the function more flexible for theming and customization.

Styling the Pagination Links

The default pagination links output as an unordered list with various CSS classes. To style the links, target classes like:

  • .page-numbers
  • .prev.page-numbers
  • .next.page-numbers
  • .current

For example, to style the current page number in bold:

.custom-pagination .current {
  font-weight: bold; 
}

Or hide the previous/next text on small screens:

@media (max-width: 600px) {
  .custom-pagination .prev,
  .custom-pagination .next {
    display: none;
  }  
}

Custom classes can also be added through the paginate_links filters mentioned earlier. This keeps styling and behavior separate.

Optimizing Pagination Performance

Pagination involves running heavy post queries multiple times. This can slow down sites significantly. Optimization techniques include:

  • Limit unnecessary queries with pre_get_posts filter
  • Adjust posts_per_page to balance page loads
  • Enable caching plugins to reduce SQL queries
  • Lazy load images/iframes below the fold
  • Server-side rendering for initial HTML
  • Async page transitions to avoid locks
  • Resize images, enable CDNs, minify CSS/JS

Optimized pagination can achieve sub-second page loads. Lossless image compression, resized media, and efficient mark up play the biggest roles.

Troubleshooting Common Pagination Issues

Some common pagination problems and fixes include:

  • Links out of sequence – Review pagination base vs requested URL
  • Page reload jumps – Compare query var values on click
  • First page shows on every click – Check rewrite rules and URL params
  • Pages render same content – Confirm $paged var increased
  • Infinite scroll lacks pages – Debug scroll trigger heights
  • No links visible – View generated source for HTML

Use debugger tools like console logging, Xdebug, Chrome Inspector or Firefox DevTools to step through the pagination logic. Activating debug plugins can also help uncover base issues.

Leave a Reply

Your email address will not be published. Required fields are marked *