Filter files by multiple file extensions

I’d like to filter files by multiple extensions.

The filter by extension function doesn’t seem to take multiple arguments.

$fonts = $page->files()->filterBy(‘extension’, ‘otf, ttf’);

I could run two separate filters but I’s prefer to have one filtered object containing all of the files in their natural order rather than printing an array of one type and then the other.

Any ideas?

Idea:
Use array( ... )to add ‘otf, ttf’.
I have not tested this.

Good luck!

Hmm, doesn’t seem to be working for me. So far the closest I’ve gotten is to do this…

In the plugins folder…
Create: f.extended.php

<?php

class fExtended extends F {

function __construct() {

self::$types['font'] = array('otf', 'ttf');

}

}

new fExtended;

?>

Then from the template:

<?php echo $page->files()->filterBy('type', 'font'); ?>

I’m sure there is a much much cleaner way to do this.

You could use a custom filter:

$fonts = $page->files()->filter(function($file) {
  return $file->extension() == 'otf' or 
         $file->extension() == 'ttf' ;
});
4 Likes

Awesome, That works great!

I’m also trying to get this to work as a custom field method.
http://getkirby.com/docs/advanced/field-methods#using-field-methods

Something similar to the way $page->images() works.

echo $page->fonts()

Thanks so much for taking a look at this.

Sorry to open up this old topic with a very specific PHP question: I have another lookup array to be used in the filter function and just noticed it’s not available – is there any way to make this available in the function or is this by PHP design?

Edit: Ok, I got it to work by using $GLOBALS – this feels pretty hacky though.