I have a search form. Choose a taxonomy, and select one or more terms. I want to paginate the results.
Here is the code:
<?php
if(isset($_POST['tax_type'])) {
$tax_type=$_POST['tax_type'];
$terms = $_POST[$tax_type];
$term_list = implode("','", $terms);
$term_list1 = implode(", ", $terms);
$term_list = "'".$term_list."'";
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$giftfinder_args = array(
'post_type' => 'products',
'posts_per_page'=>"1",
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => $tax_type,
'field' => 'slug',
'terms' => explode(',',$term_list),
),
),
);
echo '<div class="results"><span class="eyebrow">search results</span>';
echo '<div class="cat_label">“' . $term_list1 . '”</div></div>';
// the query
$giftfinder_query = new WP_Query( $giftfinder_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $giftfinder_query;
?>
<?php if ( $giftfinder_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $giftfinder_query->have_posts() ) : $giftfinder_query->the_post();
$thumb = get_the_post_thumbnail(null, 'medium');
?>
<div class="prod"><a href="<?php the_permalink(); ?>"><?php if(empty($thumb)) {echo '<div style="width:265px;height:265px;background:#eee;"></div>';} else {the_post_thumbnail('medium');} ?></a><span class="truncate"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span></div>
<?php endwhile; ?>
<div style="clear:both;"></div>
<!-- end of the loop -->
<?php
the_posts_pagination( array(
'prev_text' => __( 'Previous page', 'twentyfifteen' ),
'next_text' => __( 'Next page', 'twentyfifteen' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>',
) );
?>
<?php wp_reset_postdata(); ?>
<?php else : get_template_part( 'content', 'none' ); endif; ?>
<?php } ?>
First page is fine, but no results appear on paginated pages.
As you can see, I’m trying to use the pagination fix that turns my query into $wp_query:
// the query
$the_query = new WP_Query( $args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $the_query;
But like I said, no results beyond first page.
I was going to try pre_get_posts but I can’t figure out how to code it since every query has unique arguments based on the user’s choice of taxonomy and searched terms.
I also tried ‘add_args’ to the paginate_links() function but could not figure out how to format the resulting get string.
BTW, right now, the query just returns one post to make it easy to check pagination.
Any suggestions appreciated!
Not sure if this is the only issue, but it looks like you have a typo.
You are setting $page:
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
But looking for $paged:
'paged' => $paged,