I'm trying to set up a past events archive. Followed the guide provided by PT: craft cms guide to set up an archive.

The only difference is that I use a custom date field (dateAndTime) and not postDate. The route leads to the correct template.

The issue

When it loads the archives/agenda/2018 template (f. ex.), it displays all 2018 events (grouped by month) but also all 2019 events that where entered in Craft in 2018. This under the correct month, but obviously the wrong year. When it load the 2019 template, only the 2019 events that where entered in 2019 show up. I can't figure out where the code is wrong.


url: archives/agenda/year (token) template: _sections/archives/agenda/index


{% set firstEntryEver = craft.entries.section('agenda').orderBy('dateAndTime asc').one() %}
    {% for year in now|date('Y') .. firstEntryEver.dateAndTime|date('Y') %}
        <li><a href="archives/agenda/{{ year }}">{{ year }}</a></li>
    {% endfor %}


    <h1>{{ year }}</h1>

    {% set entriesInYear = craft.entries.section('agenda').limit(null).after(year).before(year+1).all() %}
    {% for month, entries in entriesInYear | group("dateAndTime|date('F')") %}
        <h2>{{ month }}</h2>
            {% for entry in entries %}
                <li>{{ entry.getLink() }}</li>
            {% endfor %}
    {% endfor %}

1 Answer 1


Try this:

{% set entriesInYear = craft.entries
    . dateAndTime([
        '>=' ~ year,
        '<' ~ (year + 1)

The .before() and .after() methods are convenience methods that hide the complexity of the date query on Craft's postDate field. They don't affect any other custom date fields like your dateAndTime field.

The array for your dateAndTime field condition (in the above example) is more of a Yii Framework query thing where the optional 'and' operator in the first position means all of the following conditions must apply. If omitted, it's assumed to be 'or'.

If you prefer, the array can also be expressed as a string of comma-separated conditions like so:

.dateAndTime('and, >= ' ~ year ~ ', < ' ~ (year + 1))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.