1

I'm struggling to get my head around relations. It seems overly complex for the simple thing I want to do.

I am using an entry field on my post to set relations by city. These entries are limited to a structure that has a list of cities. I am outputting a global variable that is the current location (city).

With the following code, I am able to get any posts from the current city.

{% paginate craft.entries.section("news").relatedTo(currentCityFilter).order("featured desc").limit(10) as pageInfo, pagePosts %}

{% for post in pagePosts %}
    <article>
        <h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
        <p>Posted on {{ post.postDate.format("F d, Y") }}</p>
        {{ post.body.getPage(1) }}
        <p><a href="{{ post.url }}">Continue reading</a></p>
    </article>
{% endfor %}

The problem is, I don't want to force the user to set every city when they wish to have a post display for every location.

What's the proper way to show any posts that don't have a city set and still filter posts that do have a city by the current city?

Similar question with no answer here: Get entries where relation matches or is empty

jsun
  • 113
  • 1
  • 6

1 Answers1

2

Building on this answer, and this question, here is what I would try:

Get the posts from the current city:

{% set currentCityPostIds = craft.entries.section('news').relatedTo(currentCityFilter).ids() %}

Get the posts with no city (uses search):

{% set noCityPostIds = craft.entries.section('news').search('-city:*').ids %}

Make one list of all the ids (twig merge filter):

{% set postIds = currentCityPostIds|merge(noCityPostIds) %}

Get all the posts with those ids:

{% set postsToPaginate = craft.entries.id(postIds) %}

Now you can paginate them:

{% paginate postsToPaginate.order("featured desc").limit(10) as pageInfo, pagePosts %}
Marion Newlevant
  • 12,047
  • 22
  • 55