1

I'm having a page that shows entries from two sections: news and events.

The page has the following layout:


All current event entries

  • Current event entry 1
  • Current event entry 2

All upcoming event entries

  • Upcoming event entry 1
  • Upcoming event entry 2

All news entries and all past event entries combined including pagination

  • News entry 1
  • Past event entry 2
  • Past event entry 3
  • News entry 4
  • News entry 5
  • Past event entry 6

To query the current events i use the following query

{% set entries = craft.entries()
  .section('events')
  .startDate('<= ' ~ now|date('c'))
  .endDate('>= ' ~ now|date('c'))
  .orderBy('startDate asc')
  .all()
%}

To query the upcoming events i use the following query

{% set entries = craft.entries()
  .section('events')
  .startDate('> ' ~ now|date('c'))
  .orderBy('startDate asc')
  .all()
%}

I have no idea how to query all the news and past event entries.

The query should include:

  • Query all entries from section news
  • Query all events from section events where entry.endDate < now
  • Sort all entries by post date
  • Limit to 9 and include pagination

I came this far with the query:

{% paginate craft.entries()
  .section(['events','news'])
  .limit(9)
  .orderBy('postDate asc')
  as pageInfo, pageEntries
%}

What is missing: checking the event entries to see if the endDate < now.

I can't just add .endDate('< ' ~ now|date('c')) to the query. That would hide all the news entries, ofcourse.

I did search and read a lot of posts on stackexchange. Couldn't find a solution.

Anyone that could help me with this?

  • Would it be an option to use PHP for it? – Robin Schambach May 2 '18 at 8:14
  • I would rather stick to Twig. But, how would you solve this with PHP? – Rinus May 2 '18 at 9:16
  • I would fetch the element ids with two separate queries and populate all elements in the end – Robin Schambach May 2 '18 at 9:37
  • Ah yes, ID's is the trick. Will post the solution below. – Rinus May 2 '18 at 10:42
1

Found the solution.

First get entries from section events as ID's and check endDate < now:

{% set eventsIds = craft.entries()
  .section('events')
  .endDate('< ' ~ now|date('c'))
  .ids()
%}

Then get entries from section news as ID's:

{% set newsIds = craft.entries()
  .section('news')
  .ids()
%}

Then merge those two together:

{% set entryIds = eventsIds|merge(newsIds) %}

Then paginate by id, set orderBy postDate and limit to 9:

{% paginate craft.entries()
  .id(entryIds)
  .orderBy('postDate desc')
  .limit(9)
  as pageInfo, pageEntries
%}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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