filterBy for current year

Assuming I have date fields in my pages like

Date: 2015-11-01

and I would like to get the number of pages of the actual year like

$noOfPages = $pages->find('blog', 'post')
   ->filterBy('date', '*=', date('Y'))->count();

I get zero pages in Kirby 2.2 – What am I doing wrong?

Hm, I would have expected this to work but it doesn’t. However, it works if you change the date field to sth. else, like “published”.

The reason it doesn’t work is that the date() method is a special page method that parses the date and returns the timestamp by default.

You can use a custom filter to get around that special method:

$noOfPages = $pages->find('blog', 'post')
   ->filter(function($child) {
     return $child->date('Y') === date('Y');

This works like a charm. Thanks a lot @lukasbestle

Just a quick question for my full understanding: Isn’t date() a common PHP ( function? And if so, might the problem be, that Kirby treats

->filterBy('date', …

special, by expecting a timestamp to be compared to? If also yes, this would be a bug to my understanding or at least the third value date() should be treated properly if it is no timestamp but a real date.

THX again for the help.

Btw, is there a list of names or keywords we shouldn’t use (or with caution) in blueprints? It seems to me naming a field “date” could happen quite often.

Yes, but that’s not the problem here. Kirby first uses custom Page methods before using the value in the content file to allow for custom Page models. That’s why the special Kirby page() method I linked to in the previous post takes precedence over the date field of your page.

This is a feature however. The date method allows users to simply use echo $page->date($format).

As I wrote, the special date() method has been a Kirby feature since Kirby 1, so naming your field date is actually great.

You can still access the original field value by using $page->content()->date(), which will bypass the special method. You will also need to do this for fields like url or parent, which are also all special Page methods. :wink:

This means that you can use every field name you want to. Only if the Page class has a method with the same name, you will have to use ->content() to access the original value.


I think I have learned something today and I thank you for that.

You are welcome. :smile: