Search exclude pages from results

Hi,

As is it mentionned in the title, I would like to make a search function, excluding multiples pages.
I tried to make one by copying a thread I found here, but I’m not sure this is the right method : instead of ignoring some pages, I try to filterBy the pages where the search needs to be executed.

<?php

return function($site, $pages, $page) {

    $query   = get('results');
   
    $exclude = $site->index()->visible()->filter(function($child) {
        return $child->hasTemplate() == 'works' or
            $child->hasTemplate() == 'bio' ;
    });

    $results = $exclude->search($query, array('words' => true));

    return array(
        'query'   => $query,
        'results' => $results,
    ); 

};

But here, ‘Bio’ or ‘Works’ are always returned

Based on my own search that filters out certain pages by template, try this… amend ‘title|text’ for the names of the content fields you want to search through…

<?php
return function($site, $pages, $page) {

  // Search Results
  $query = get('results');

  // Filter the result....
  $results = $site->search($query, 'title|text')->visible()->filterBy('template', 'not in', ['works', 'bio']);

  // Pass these off to the template
  return compact('query', 'results');

};

It makes more sense to limit the pages first, then search. Otherwise, you search within pages that you don’t even have to touch. @oziris Your logic is the wrong way round, because you want to exclude those pages, not use only those pages.

Houuuu very nice, thanks ! This works great, I didn’t found it but this is mentionned in Filtering Compendium.

You welcome, but i did make a small mistake… as @texnixe says, do the filter first, then search the remaining pages.

Oki doki, thanks !

<?php

return function($site, $pages, $page) {

    $query   = get('results');

    $results = $site->index()->visible()->filterBy('template', 'not in', ['works', 'bio'])->search($query, array('words' => true));

    return array(
        'query'   => $query,
        'results' => $results,
    ); 

};