Custom filters in Kirby 3

Hello,

I am working on converting a rather complex Kirby 2 site to Kirby 3. One snag we seem to be hitting is in using a custom filter used to greatly simplify our publishing workflow.

Back in K2, there was a great way of defining custom filters via a plugin:
https://k2.getkirby.com/docs/developer-guide/objects/collections#define-your-own-method

How ought we go about this in K3?

FWIW our filter is used widely across the site and It’d be great to avoid using a callback function in each implementation. In our case we’re simply filtering by date/time:

K2 code:

collection::$filters['datefilter'] = function($collection,$field,$value) {
  foreach ( $collection->data as $key => $item ) {
    $datetime = collection::extractValue($item,$field);
    if ( !$datetime || strtotime($datetime) < $value ) {
      continue;
    }
    unset($collection->$key);
  }
  return $collection;
};

Thank you!

Yes, undocumented, but collectionFilters are a possible extension and can be registered with Kirby’s plugin wrapper like any other extension.

Kirby::plugin('your/plugin', [
    'collectionFilters' => [
      'datefilter' => function ($collection, $field, $test, $split = false) {
  
         foreach ($collection->data as $key => $item ) {
              $datetime = $collection->getAttribute($item, $field, $split, $test);
              if (!$datetime || strtotime($datetime) < strtotime($test) ) {
                  continue;
              }
              unset($collection->$key);
          }
          return $collection;
      }
    ]
]);

Now also in the docs: https://getkirby.com/docs/reference/plugins/extensions/collection-filters

Thank you, Sonja!