I setup my archive using the Craft demo. I have a page for each year.

I use MixItUp,(think Isotope) to allow a user to filter entries by month. There are simple hard coded buttons for each month.

How can I loop through the entries and create a button for only those months that have entries?

Update. I have a loop that pulls all the entries for a given year. I then use MixItUp (think Isotope) to filter the entries by month.

There is a button for each month that triggers MixItUp. I want to make the creation of these buttons dynamic. That is, I want to create a loop that generates a button for only those months that contain entries and create a class with the month's name that corresponds with the month in the class names of the entry cards.

For any given year, the loop would create 1-12 buttons.

{% for month that has > 0 entries %}

<button type="button" class="btn btn-outline-secondary btn-lg"   data-mixitup-control data-filter=".February">Feb</button>

{% endfor %}

enter image description here


1 Answer 1

{% set date = (date()).modify('first day of january 00:00:00') %}
{% for month in 1..12 %}
    {% set endOfMonth = clone(date).modify('last day of this month') %}
        {% set exists= craft.entries
            .postDate(['and', '>=' ~ date.format('-.m-d H:i:s'), '<=' ~ endOfMonth.format('Y-m-d H:i:s') ])

    {% do date.modify('first day of next month') %}
{% endfor %}

loop all months and check if there are entries in this month or not

  • I am not getting it. I updated my question. I can't seem to get this to pull only those months with entries.
    – Hellyar
    Commented Jul 6, 2018 at 13:09
  • What doesn't work... "I don't get it" is not really helpful. My code loops all months and tries to fetch the corresponding entries where postDate is within this month, if entries with such a condition exists -> if the exists variable is true you can display the button, if exists is not true the month doesn't have entries Commented Jul 6, 2018 at 13:11

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.