Standard WordPress category or tag archive pages usually handle pagination automatically. However, when we are using get_terms() to list all terms within a custom taxonomy on a specific page, or if we have a very large number of categories and want to provide a paginated list, we need to implement pagination ourselves. The paginate_links() function is the gold standard for creating numbered pagination in WordPress.
Using get_terms() with Pagination
To implement pagination for taxonomy terms, we first need to determine the current page number and the number of terms to display per page. Then we calculation the offset for the get_terms() query.
$per_page = 20;
$paged = max(1, get_query_var('paged'));
$offset = ($paged - 1) * $per_page;
$args = [
'taxonomy' => 'product_cat',
'number' => $per_page,
'offset' => $offset,
];
$terms = get_terms($args);
$total_terms = wp_count_terms('product_cat');
$total_pages = ceil($total_terms / $per_page);
Generating Pagination Links
After fetching the specified terms for the current page, we use paginate_links() to output the navigation.
echo paginate_links([
'base' => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))),
'format' => '?paged=%#%',
'current' => $paged,
'total' => $total_pages,
'prev_text' => '« Previous',
'next_text' => 'Next »',
]);
Important Parameters
- base: Used to reference where the pagination links are.
%#%is replaced by the page number. - total: The total number of pages. We calculated this using
ceil($total_terms / $per_page). - current: The current page number.
Conclusion
Manually implementing pagination for taxonomies gives you precise control over which terms are displayed and how the navigation looks. This is especially useful for creating “Index” or “Directory” pages in WordPress where you need to list a vast amount of metadata in an organized fashion.
