1

Trying to pull in a limit of 2 events that are upcoming (so the event's eventDate should be newer than today). I currently have this:

{% set entries = craft.entries.section('events').order('eventDate asc') %}
{% set today = now|date('Y-m-d') %} 

{% for event in entries %}
  {% if today <= event.eventDate %}
    <!-- markup here -->
  {% endif %}
{% endfor %}

However, this returns all events that are upcoming. I would like to only limit it to 2. The problem when I put the .limit(2) on my for loop is that it chooses the first two (and those happen to be older events). Do I need to do another loop within the if statement and add .limit(2) to that or is there a better way?

Thanks!

dace
  • 241
  • 2
  • 9

1 Answers1

5

This should work below. Rather than querying all entries and looping through, just select the entries you need (ie. now) and limit them.

{% set upcomingEvents = craft.entries.section('events').eventDate('>= '~now).limit(2) %}
{% for event in upcomingEvents %}
    <!-- markup here -->
{% endfor %} 
Siebird
  • 373
  • 1
  • 11
  • Hi, thanks. Just tried this but its giving me a "Fatal error: Call to a member function getTimestamp() on boolean" with a large call stack table. – dace Aug 05 '16 at 19:23
  • Should also clarify that the date I need to make sure it's displaying after today is the eventDate of the entry (a custom field I set) and not the published or posted date. – dace Aug 05 '16 at 19:26
  • 1
    I guess .after('>= '~now) should be .eventDate('>= '~now), otherwise this looks solid. – Mats Mikkel Rummelhoff Aug 05 '16 at 19:53
  • Yes!! Thanks! Using ".eventDate(...)" worked for me. Appreciate the help!! – dace Aug 05 '16 at 21:29