Skip to content

Kirby 3.6.6

Search

Add your own search engine

If you are not happy with our built-in search for collections, you can create your own.

Keep in mind that the search component will be used for all searches of collections (e.g. pages, users, fields) that use the ->search() method.

/site/plugins/my-search/index.php
<?php

use Kirby\Toolkit\Collection;

Kirby::plugin('my/search', [
  'components' => [
    'search' => function (Kirby $kirby, Collection $collection, string $query = null, $params = []) {
      // only search in the field named keywords
      $result = $collection->filterBy('keywords', '*=', $query);

      return $result;
    }
  ]
]);

To replace the search for just one specific type of collection (e.g. for pages only), fall back on Kirby's native component for the rest:

/site/plugins/my-search/index.php
<?php

use Kirby\Toolkit\Collection;

Kirby::plugin('my/search', [
  'components' => [
    'search' => function (Kirby $kirby, Collection $collection, string $query = null, $params = []) {
      // only replace the search component for Pages collections
      if (is_a($collection, 'Kirby\Cms\Pages') === true) {
        // only search in the field named keywords
        $result = $collection->filterBy('keywords', '*=', $query);

        return $result;
      }

      // use the native component for other searches (users, files...)
      return $kirby->nativeComponent('search')($kirby, $collection, $query, $params);
    }
  ]
]);

Parameters

Name Type Default Description
$kirby * Kirby\Cms\App Kirby instance
$collection * Kirby\Cms\Collection Collection of searchable models
$query string null
$params mixed [ ]

Return type

Kirby\Cms\Collection|bool