5

How could I go about fetching all assets that are not currently beeing used anywhere?

7

With good help from @carlcs here and on Slack, we found a solution:

{% set allEntryIds = craft.entries.limit(null).ids() %}

{% set usedAssets = craft.assets({
    relatedTo: allEntryIds,
    limit: null,
}).ids() %}
{% set unusedAssets = craft.assets({
    id: 'and, not ' ~ usedAssets|join(', not '),
    limit: null
}) %}
2
  • 2
    Keep in mind, this is for all assets not used by entries only, they could be used by other elements like craft commerce products. May 29 '17 at 10:29
  • Yes, and even other assets I discovered :)
    – megatrond
    May 29 '17 at 11:11
1

Update: This solution doesn't work, but no-one can explain why (maybe a Craft bug?). I'm leaving the code for reference though.

--

You could get them with a craft.assets element criteria model and a relatedTo param. Just pass a 'and, not 8, not 13, not 26' type of string to sourceElement, with all element IDs listed that you want to exclude from an otherwise limit: null assets query.

{% set allEntryIds = craft.entries.limit(null).ids() %}
{% set allCategoryIds = craft.categories.limit(null).ids() %}

{% set omitIds = allEntryIds|merge([allCategoryIds]) %}
{% set idsParam = 'and, not ' ~ omitIds|join(', not ') %}

{% set unusedAssets = craft.assets({
    relatedTo: {
        sourceElement: idsParam,
    },
    limit: 0,
}) %}
1
  • I get an "Array to string conversion" error on the line where you join the omitIds, is there a way around that?
    – Jai Sandhu
    Sep 10 '18 at 13:30

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.