Search code examples
phpwordpresspaginationstandardized

Standardized and simple WordPress pagination options


I want my Wordpress pagination to consistently have 5 numbers in it. I want it to always be:

< previous 1 2 3 4 ... 37 next >

< previous 5 6 7 8 ... 37 next >

While I know there are several ways of developing this pagination and countless different posts relating to this subject, I find most of the answers are specific to the way the dev needs the nav setup. As a result, I find myself often looking this up every time I go to implement a WordPress pagination for a client.

The point of this post is to have a standard blueprint to reference that can be customized and consistently implemented. In addition, I'd like simple and clean code with WordPress coding standards in mind. Not to interested in any hacky way of doing this.

I'll be adding my answer to this post as well and hoping to get a few different standardized methods available for WordPress devs to chose from.

Pagination Requirements:

Items with stars(*) are ideally customizable

  1. 1 set of dots before the last page
  2. *4 page numbers prior to ...
  3. *1 page number after dots
  4. For simplicity, no CSS or styling of any sorts, only PHP & minimal HTML markup of the nav
  5. No hacks

Solution

  • functions.php or if using namespaces in your theme like I do inc/core.php

    namespace Theme_Name\Core; // only if using namespaces
    
    ...
    
    /**
     * Archive post pagination
     */
    function archive_pagination() {
        $current_page = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
        $mid_size = $current_page === 1 ? 3 : 2;
    
        the_posts_pagination(
            array( 'mid_size' => $mid_size )
        );
    }
    
    

    Adding it in archive.php or archive-CATEGORY.php

    // namespaces
    
    use Theme_Name\Core;
    
    <?php Core\archive_pagination(); ?>
    
    
    // Regular function
    
    /* personally I would update the function's name to themename_archive_pagination */ 
    archive_pagination();