Skip to content

Kirby 3.8.4

Collection methods

Collection methods are registered with the collectionMethods extension.

They are used for all CMS collections (Files, Pages and Users as well as Structure, Languages...) whenever:

  • there is no built-in method or
  • a more specific files, pages or users method.

Default collection methods

For a full list of default collection methods, please check out the Reference.

Be aware that you cannot override these default collection methods with any custom collection method.

Getting started

You can extend the set of defined collection methods in a plugin file.

/site/plugins/collection-methods/index.php
Kirby::plugin('my/plugin', [
    'collectionMethods' => [
         'toCustomArray' => function () {
            return $this->toArray(function ($item) {
                return $item->id();
            });
        }
    ]
]);

This example shows the basic architecture of a collection method. You define the method name with the key for the collectionMethods extension array. $this in the callback function refers to the $collection object.

The example will return an array of collection item IDs.

Working with method arguments

In some cases it might be helpful to be able to pass arguments to the method.

You can define arguments for a method like this:

/site/plugins/collection-methods/index.php
Kirby::plugin('my/plugin', [
    'collectionMethods' => [
         'toCustomArray' => function ($field) {
            return $this->toArray(function ($item) use ($field) {
                return $item->$field();
            });
        }
    ]
]);

And then use it like this:

<?= $collection->toCustomArray('title') ?>

This example will return the titles of all collection items.