0

How can I create a search bar for a page that searches only in particular page IDs? This shouldn't affect the search bar on other pages.

I tried the following:

 add_filter( 'pre_get_posts', 'pregetposts_forspecificpage' );

    function pregetposts_forspecificpage($query){
       if ($query->is_search) {
       $query->set('post_type', 'page');
       $query->set('post__in', array(22103,22121));
       }
       return $query;
    }

But this affects search bars used on other pages.

0

You can try to modify your filter like this

function pregetposts_forspecificpage($query){
   if(!is_admin() && $query->is_main_query() && is_search())
   {
     $query->set('post_type', 'page');
     $query->set('post__in', array(22103,22121));
   }
}

Edit : added !is_admin() because we only want to alter the query in the front. $query->is_main_query() to be sure that we are altering the main query. Replaced $query->is_search by is_search()

Also, you don't have to return the $query.

2
  • Tried the above filter. It is not searching in those particular page id's specified in array. – Karonlps Nov 19 '15 at 12:47
  • When you use the search bar, do you want the results to be display in the search.php template ? You could add a from get parameter to know from which page the search was triggered – Sladix Nov 23 '15 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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