search with pagination not working as expected

Why is this url pattern taking me to a 404 page where i saw in some other sites this same pattern works fine with search and paginate please help me i am new to wordpress and don't know why this is happening anyone who is experienced can tell me whats wrong here looking for helpful answers , thanks in advance

$search = get_query_var(s);
$page_num = get_page_num();

$query = new WP_Query(array(
    posts_per_page = 4,
    paged = $page_num,
    post_type = post,
    s     = $search
));   

get_page_num in functions.php:

function get_page_num(){
    $name = is_front_page() ? page:paged;
    $page = get_query_var($name);
    $page = esc_html($page);
    $page = $page ? $page:1;
    return $page;
}

Topic paginate-links pagination Wordpress

Category Web


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:

https://developer.wordpress.org/reference/hooks/pre_get_posts/

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.