Recently I have faced a pagination problem with the custom post type on the custom archive page. It was showing a 404 page when I select page/2. I have Googled a lot and didn’t find the exact solution. Finally, I fixed the problem and I am sharing the code maybe it could help you.
My custom post type name: testimonials and my category name: testimonial-cat.
Plugin I used: SuperCPT and WP-PageNavi.
function.php
// function.php // Testimonial Pages $testimonial = new Super_Custom_Post_Type( 'testimonial', 'Testimonial', 'Testimonials', ['hierarchical'=> true, 'publicly_queryable' => true, 'query_var' => true, 'rewrite' => ['slug' => 'testimonials', 'with_front' => false, 'pages' => true]] ); $testimonial_cat = new Super_Custom_Taxonomy( 'testimonial-cat', 'Testimonial Category', 'Testimonial Categories', 'category' ); $testimonial->add_to_columns( 'trip_code' ); $testimonial->add_to_columns( 'testimonial-cat' ); $testimonial->set_icon( 'comments' ); connect_types_and_taxes($testimonial,array($testimonial_cat)); } add_action( 'after_setup_theme', 'custom_post_type' ); // Flush rewrite rules for custom post types add_action( 'after_switch_theme', 'flush_rewrite_rules' ); function flush_rewrite_rules() { flush_rewrite_rules(); } // Fix 404 issue function testimonialPagination( $query ) { if( $query->is_main_query() && !$query->is_feed() && !is_admin() ) { $query->set( 'paged', str_replace( '/', '', get_query_var( 'page' ) ) ); } } add_action('pre_get_posts','testimonialPagination');
I created a custom archive page(archive-testimonial.php) to show my posts.
<?php //archive-testimonial.php //$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // Did'nt work global $wp; $url = home_url(add_query_arg(array($_GET), $wp->request)); if(preg_match("/\/(\d+)$/",$url,$matches)) { $paged=$matches[1]; } else { $paged = 1; } //$args = array( 'post_type' =>'testimonial', 'posts_per_page' =>3 , 'page' => $paged, 'paged' => $paged ); $args = array( 'post_type' => 'testimonial', 'posts_per_page'=>get_option('posts_per_page'), 'paged' => $paged ); $the_query = new WP_Query($args); ?> <section class="archive-posts" > <?php if (!have_posts()) : ?> <div class="alert alert-warning constrained"> <?php _e('Sorry, no results were found.', 'roots'); ?> </div> <?php endif; ?> <div class="posts__inner"> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php get_template_part('templates/list-testimonial', get_post_type()); ?> <?php endwhile; ?> </div><?php wp_pagenavi( array( 'query' => $the_query ) ); ?> </section> <?php wp_reset_postdata(); ?>
That’s it! Hope it will help you.