9

I have a structure people that I need to grab entries from. However, I need to exclude certain entries as some are already displayed on the page in a different manner.

I know that you can exclude a single entry by doing something like this

{% for councilMember in craft.entries.section('people').id('not ' ~ entry.id)

But how do you exclude multiple entries by their IDs?

10

In my case I have a set number of chosen entries to exclude so I'll show how to do that first.

{# Build array of chosen council leaders to exclude from council member list since they're already being displayed by using the "merge" Twig filter #}
{% set idsToExclude = ['and'] %} 

Beginning the array with 'and' is the trick here. Without it this won't work.

{% set idsToExclude = idsToExclude|merge([entry.metropolisCouncilPresident.first.id]) %}
{% set idsToExclude = idsToExclude|merge([entry.metropolisCouncilVicePresident.first.id]) %}
{% set idsToExclude = idsToExclude|merge([entry.metropolisCouncilSecretary.first.id]) %}
{% set idsToExclude = idsToExclude|merge([entry.metropolisCouncilTreasurer.first.id]) %}

{# Convert the idsToExclude array into a comma separated list #}
{% set idsToExcludeString = idsToExclude|join(', not ') %}

{# Echo out the council members without displaying the featured ones #}
{% for councilMember in peopleEntries.id(idsToExcludeString) %}
  {{ councilMember.title }}
{% endfor %}

Let's say you want to exclude entries that you've choosen in a entry field. So there's multiple related entries and you've already looped over them to display them on the page but you want to ensure that they aren't displayed later on the page when you list all the entries out.

It's fairly similar to the above code but just for the sake of clarity.

{# Base array of chosen council members to exclude from council member list since they're already being displayed #}
{% set idsToExclude = ['and'] %} 

{% for item in entry.featuredCouncilMembers %}
  {{ entry.title }}

  {# Build array of chosen council leaders to exclude from council member list since they're already being displayed by using the "merge" Twig filter #}
  {% set idsToExclude = idsToExclude|merge([item.id]) %}
{% endfor %}

{# Convert the idsToExclude array into a comma separated list #}
{% set idsToExcludeString = idsToExclude|join(', not ') %}

{# Echo out the council members without displaying the featured ones #}
{% for councilMember in peopleEntries.id(idsToExcludeString) %}
  {{ councilMember.title }}
{% endfor %}
  • 3
    You might want to check for idsToExclude length before joining and passing it to the id param, to make sure to not pass a string with 'and' only. Thanks for the nice post! – carlcs Dec 8 '15 at 23:00

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.