I initially thought you’re using the code in the question on a Page (a post of the type page
), but if you are actually using that code on an archive-based page (e.g. the home page, a category page, etc.), then the 404
error is normal. You can’t paginate secondary/custom query on archive-based pages. Well, not when using the default paged
query string in the URL.
So a possible solution is use a Page and make your custom loop in there — basically, the code in the question would work after you made the changes I mentioned in the original answer. I.e.:
-
Change the
base
argument in yourpaginate_links()
call:// change from this 'base' => str_replace( $big, '%#%.html', esc_url( home_url( '/<slug>/page/' . $big ) ) ) // to this 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) )
-
And in addition to that
base
, you also need to change the'total' => 6
to'total' => $testimonials->max_num_pages
. (more details here)
But if you actually wanted to customize the main query, then use the pre_get_posts
hook.
So for example, if your home page is set to show the latest posts, but you want to include only posts of the type blog_post
, then you can simply add this to your theme’s functions.php
file:
add_action( 'pre_get_posts', function ( $query ) {
if ( ! is_admin() && $query->is_main_query() && is_home() ) {
$query->set( 'post_type', 'blog_post' );
$query->set( 'posts_per_page', 2 );
}
} );
And that’s really all you need. I.e. No need to worry about the pagination because a good theme always includes a working pagination for the main query on the home page and other archive-based pages.