Send arguments to collection filter

This does not work:

$my_variable = 'Hello there!';

$collection = page('projects')->children()->filter(function($child) {
  echo $my_variable;
});

That’s because they are in different scopes.

Solution:

$my_variable = 'Hello there!';

$collection = page('projects')->children()->filter(function($child) use ($my_variable) {
  echo $my_variable;
});

Inside the filter you should return true or false depending on a condition. This just illustrates that the variable are sent to the function successfully. :slight_smile:

More about filters:

Or check out the filtering recipe: https://getkirby.com/docs/cookbook/filtering

1 Like