How to exclude pages in Site wide Search

I have a simple site-wide search page. In my search.php controller, I’m attempting to have the search NOT include a page (‘members’) and its children pages. I tried ‘not’ method and ‘not in’ but it still searches all of the pages.

This code does NOT work:

$results = $site->search( $query, ‘title|text|blocks’ )->listed()->not([ page( ‘members’ ) ]);

I also tried this:

$results = $site->search( $query, ‘title|text|blocks’ )->listed()->filterBy( ‘pages’, ‘not in’, [ ‘members’ ]);

I know I can filter by templates and tags but is there a way to filter by pages or exclude certain pages when doing a site-wide search?

$excluded = page('members')->children();
$excluded = $excluded->add(page('members');
$results = $site->search( $query, ‘title|text|blocks’ )->listed()->not( $excluded);

Although it would probably make more sense to filter the page to search first, not the results?

Thank you for your quick response. I had to add the listed() method to be able to use the add() method. The page wouldn’t display even in debug mode. Not sure why that is because both the children() and listed() return the same type.

$excluded = page( 'members' )->children()->listed();
$excluded->add(page('members'));
    
$results = $site->search( $query, 'title|text|blocks' )->listed()->not( $excluded );

The above code works for the main page and its children, but it doesn’t exclude any grandchildren or any deeper subpages.

So I modified the code to use the index() method. That works. However, I know the index() method can be pretty heavy since it’s looking through the entire contents including files. Is there another way besides using that method to exclude the parent ‘members’ page and all of it’s subpages?

$excluded = page( 'members' )->index()->listed();

$results = $site->search( $query, 'title|text|blocks' )->listed()->not( $excluded );

The warning basically refers to using $site->index() in large installations. Of course, if you your members page also has thousands of subpages in the tree, you might run into the same issue. I hope, that is not the case, otherwise, you will have to cache the collection.

1 Like