0

I have a search page with pagination, that is displaying the correct number of pages, however it the links seem to be forwarding to the 404 page.

$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$search_args = array(
    'posts_per_page'    => 2,
    's'                 => get_search_query(),
    'post_status'       => 'publish',
    'post_type'         => 'post',
    'paged'             => $paged,
);
$search = new WP_Query($search_args);
$big = 999999999; // need an unlikely integer
$pagination_args = array(
    'base'      => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
    'format'    => '?paged=%#%',
    'current'   => max( 1, get_query_var('paged') ),
    'mid_size'  => 2,
    'total'     => $search->max_num_pages
);

echo paginate_links($pagination_args);

Any help as to why these links might be broken would be a huge help!

6
  • Any particular reason you're using a custom query for the search page? Jul 17, 2018 at 14:35
  • No reason, other than I'm new to this, and couldn't work out another way of doing it. If you have a better recommendation, please let me know! Jul 17, 2018 at 14:45
  • When you create templates following the template hierarchy the main query, whose posts you loop through with have_posts() and the_post() (without $search-> or anything like that) will have the correct posts already in it. Then you can use functions like paginate_links() without needing to specify any of the arguments. Jul 17, 2018 at 14:49
  • Correct me if I'm wrong, but wouldn't using have_posts() and the_post() mean that you wouldn't be able to give loop a search query from an input form? Jul 17, 2018 at 14:56
  • 1
    If you use the standard WordPress search form, with get_search_form() or the widget, then you will be taken to /?s={search term here}. On that page the main query will be populated with results for that search. The template that's loaded will be based on the hierarchy (so search.php if it exists, otherwise index.php). Jul 17, 2018 at 15:00

1 Answer 1

0

Answer provided in the comments:

global $wp_query;
$big = 999999999; // need an unlikely integer
$pagination_args = array(
    'base'      => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
    'format'    => '?paged=%#%',
    'current'   => max( 1, get_query_var('paged') ),
    'mid_size'  => 1,
    'total'     => $wp_query->max_num_pages
);
if(have_posts()):
    while(have_posts()):
        the_post();
        //individual search result
    endwhile;
    wp_reset_postdata();
    echo paginate_links($pagination_args);
endif;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.