Use paginate_links() to Add Pagination for WordPress Category and Tag Lists

We already know that WordPress has built-in pagination for post lists and comments. User lists and taxonomy term lists can be paginated too. Once you understand the pagination principle, almost anything can be paginated.

For taxonomy term lists, the two required pieces of data are $number and $offset. $number controls how many items are shown per page, while $offset determines where the query should start retrieving terms.

Prepare the category or tag data

paginate_links() needs the current page number and the total number of pages. get_terms() needs the number of items per page and the offset. The following code prepares all of those values.

$taxonomy = 'post_tag';
$number   = 100;

// Pagination parameters.
$page       = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$offset     = ( $page > 0 ) ? $number * ( $page - 1 ) : 1;
$totalterms = wp_count_terms( $taxonomy, [ 'hide_empty' => true ] );
$totalpages = ceil( $totalterms / $number );

$terms = get_terms( [
    'taxonomy'   => $taxonomy,
    'number'     => $number,
    'offset'     => $offset,
    'hide_empty' => true,
] );

Once the data above is prepared, pass the values into paginate_links() and the taxonomy list can use pagination just like a normal post archive.

$big = 999;

echo paginate_links( [
    'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format'    => '',
    'current'   => max( 1, $page ),
    'total'     => $totalpages,
    'prev_text' => 'Previous',
    'next_text' => 'Next',
] );

Of course, you can also write your own pagination function if you want richer visual output or more advanced behavior. But for many projects, paginate_links() is already enough.

Related Posts

Leave a Reply

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