See edit at bottom.
I have a wp_query loop in a page template for a custom post type ("success_stories"). The loop itself works fine but I cannot seem to get pagination working. I've tried every solution I could find on these forums and everytime I try to navigate to /page/child-page/page/2/ WordPress sends me back to /page/child-page/ with a 301 redirect.
I have of course flushed the permalinks about 100 times. Here's the code I'm working with:
<?php
if ( get_query_var('paged') ) {
$paged = get_query_var('paged');
} elseif ( get_query_var('page') ) { // 'page' is used instead of 'paged' on Static Front Page
$paged = get_query_var('page');
} else {
$paged = 1;
}
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// Query arguments
$args = array(
'post_type' => array( 'success_stories' ),
'posts_per_page' => '3',
'paged' => $paged,
'ignore_sticky_posts' => true,
'tax_query' => array(
array(
'taxonomy' => 'practice_areas_taxonomy',
'field' => 'ID',
'terms' => array( 17 ),
)
)
);
// Instantiate custom query
$practice_area_query = new WP_Query( $args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $practice_area_query;
// Output custom query loop
if ( $practice_area_query->have_posts() ) :
echo '<div>';
while ( $practice_area_query->have_posts() ) :
$practice_area_query->the_post(); ?>
<div class="<?php echo $pa_class_inner; ?>">
<blockquote>“<?php echo get_the_excerpt();?>”</blockquote>
</div>
<?php endwhile;
echo '</div>';
endif;
// Pagination
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1) {
$big = 999999999;
$current_page = max(1, get_query_var('paged'));
echo '<nav class="pagination clearfix">';
echo paginate_links(
array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'current' => $current_page,
'total' => $total_pages,
'prev_text' => 'Prev',
'next_text' => 'Next',
'mid_size' => 1,
'end_size' => 3
)
);
echo '</nav>';
}
wp_reset_postdata();
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query; ?>
Where am I going wrong? Can this not be done from a (child?) page template?
Edit: adding the following rewrite rules almost resolves the issue:
// Primary Rewrite Rule
add_rewrite_rule( 'practice-areas/family-law/?', 'index.php?post_type=success_stories', 'top' );
// Pagination Rewrite Rule
add_rewrite_rule( 'practice-areas/family-law/page/([0-9]{1,})/?', 'index.php?post_type=success_stories&paged=$matches[1]', 'top' );
The only problem then is that (a) on paginated pages I'm suddenly in a different template (archive.php) and (b) WordPress seems to default to regular wp_query parameters. That is, it's "forgotten" all my args from the above query, as well as my offset, and I think even the taxonomy query.
$total_pages = $practice_area_query->max_num_pages;
instead of having to do those$temp_query
things.pre_get_posts
filter to modify the parameters of the query instead of creating a second query?page