I’ve made quite a few WordPress themes in my time, and so I thought I would write a few blog posts sharing some of the code snippets that I find myself using repeatedly.
First off is some numeric pagination using native WordPress functionality. I have always prefered numbered pagination over next and previous links as it gives a good indication of progression and location – and allows you to skip around much more quickly – but WordPress doesn’t have a single line command for it.
For a long time I used my own custom function – but now I use the function below.
The function that does all the clever stuff is the paginate_links command. For WordPress it’s mostly used in the admin, but it’s easy to reuse as shown below.
/**
* numeric pagination for custom queries
* Much nicer than next and previous links :)
*
* @global type $wp_query
* @param type $pageCount
* @param type $query
* @return type
*/
function bm_numeric_pagination( $page_count = 9, $query = null ) {
if ( null == $query ) {
global $wp_query;
$query = $wp_query;
}
if ( 1 >= $query->max_num_pages ) {
return;
}
$big = 9999999999; // need an unlikely integer
echo '<div id="archive-pagination pagination">';
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $query->max_num_pages,
'end_size' => 0,
'mid_size' => $page_count,
'next_text' => __( 'Older ›', 'textdomain' ),
'prev_text' => __( '‹ Newer', 'textdomain' )
) );
echo '</div>';
}
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.