3

is it possible to grab all the entries in a section that arent related to a category?

So something like

craft.entries.section('news').relatedTo('not',category)

Doesnt seem to work but is there some other syntax?

Keith Mancuso
  • 2,421
  • 16
  • 27

4 Answers4

8

If you want to do it in a single query, Marion's answer is probably the best.

Otherwise, you could do something like this:

{% set idsHavingCategory = craft.entries.section('news').relatedTo(category).limit(null).ids() %}

{% set omitIds = 'and, not ' ~ idsHavingCategory|join(', not ') %}

{% set entries = craft.entries.section('news').id(omitIds) %}

Inspired by this article, which shows how to (1) grab ids, and (2) query against them:

http://webstoemp.com/blog/manipulating-craft-elementcriteriamodel-with-twig/

Also references related solutions found in these answers:

Lindsey D
  • 23,974
  • 5
  • 53
  • 110
  • I know, old question. But any idea how to combine this with a separate query? I'm looking to list entries that either do not have a category, or a specific category. It's proving to be quite a challenge. – InanisAtheos Mar 08 '22 at 15:20
  • 1
    @Athoxx If you want to merge two queries, here is an old article (it describes Craft 2) which does a great job of explaining the basic concept. Perform both queries and get ids, then use the IDs in a follow up query. – Lindsey D Mar 08 '22 at 18:25
5

I got this to work with search:

{% set uncategorizedEntries
  = craft.entries.section('news').search('-category:*') %}

Here category is the category field. You are searching everything in news which does not have a category field that matches *.

Marion Newlevant
  • 12,047
  • 22
  • 55
  • hmm yea i guess that would work but i cant imagine thats very performant. Hoping theres a more direct route to get this to work but maybe not yet. – Keith Mancuso Jul 03 '15 at 14:52
3

Another approach -- that might work for you -- is to filter on the output, rather than the query. For instance, using this query:

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

Output using this loop:

{% for entry in entries if entry.category is empty %}
    ...
{% endfor %}

YMMV

1

Not sure if this will help much, but I did something similar with:

{% set allNews = craft.entries.section('news') %)

Then:

{% for entry in allNews.id("not #{category.id}") ... {% endfor %}

Hope that helps in some way.

Nicolaides
  • 11
  • 3