I recently had an issue with pagination on a custom page template for a loop, whenever page 2 or beyond was loaded the page 404’ed, nightmare.

Whilst building your WordPress site you may occasionally come across the need to use a page (with a template) as a custom archive page; for example, should you want to gather all your posts which have a specific meta value in one place. This is normally achieved by creating a custom template which contains, amongst other things, your loop of the posts you want to show, its simple, it works.

That is, until pagination.

Once you try to paginate that page using /page/2, you probably have encountered the 404 page.

After much experimenting, I have worked out this one piece of code that solve the problem. All you need to do is update the code to fit what you need and add it to your theme’s function file:

add_action( 'init', function(){
add_rewrite_rule( '^{archive-page}/page/([0-9]+)/?', 'index.php?page_id={page-id}&paged=$matches[1]', 'top' );

Replace archive-page with the slug of the page you are using for your archive, and the page-id with the corresponding page id.

Once added you will need to flush your permalink rules (Setttings > Permalink > Save), and you should be good to go.