paginate links – search with pagination not working as expexted


The reason your search query fails is because you threw away the main query and created a brand new secondary query. Your secondary query has a second page, the main query does not. The main query is what is important, and because it has no second page, a 404 is shown, which is correct behaviour.

Instead of ignoring the main query, modify it. If you want the main query to only show 4 results per page in a search, make it only show 4 results per page when searching. Don’t discard it and use new WP_Query with posts_per_page set to 4. Use the pre_get_posts filter to change posts_per_page to 4 in the main query.

A trivial filter in the functions file would have given you what you wanted all along:

add_action( function( WP_Query $query ) {
    if ( $query->is_search() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 4 );
} );

With that, a standard post loop and standard pagination work out the box with no custom queries necessary. This is both faster and simpler than new WP_Query

is there any way i can make WP_Query to as default ?

Yes but:

  • it’s extreme bad practice
  • it will not fix your problem as anything in the template is too late
  • it will introduce new problems
  • you would still have double the number of queries needed
  • the main query is already a WP_Query, the problem is that you created a new one, this is bad practice.

If you want to modify the main query, modify it via pre_get_posts, don’t create a new one.

I strongly recommend reading the pre_get_posts documentation, it will save you a lot of time and make things clearer:

Amir Rahman 1 year 2021-11-06T15:04:24-05:00 0 Answers 0 views 0

Leave an answer