How can I alter the WordPress query without “overriding” it?

I have a search results page that I want to limit results on i.e. posts_per_page. However if I use query_posts('posts_per_page=6') I lose the original query.

How do I alter my query without damaging the original?

Related posts

2 comments

  1. You can use the pre_get_posts filter to access/alter the $query object. In functions.php:

    function search_filter($query) {
      if ( !is_admin() && $query->is_main_query() ) {
        if ($query->is_search) {
          $query->set('posts_per_page', 6);
        }
      }
    }
    add_action('pre_get_posts', 'search_filter');
    
  2. Never ever use query_posts, it breaks the main query object ($wp_query) and all functionality that relies on the main query object. It also breaks page functionality. Apart from that, it is slow and reruns queries. query_posts should be on top of your most evil list together with functions like create_function(), eval() and extract().

    If you need to alter the main query, always use pre_get_posts to do so. Never change the main query with a custom one, it might solve one problem, but it creates many other.

    The following will work

    add_action( 'pre_get_posts', function ( $q )
    {
        if (    !is_admin()
             && $q->is_main_query()
             && $q->is_search()
        ) {
            $q->set( 'posts_per_page', 6 );
        }
    });
    

Comments are closed.