I want to be able to delete assets that are not linked to. I have adapted the following code from previous examples of this kind of thing, but it doesn't seem to pick up all the related entries, just some of them. Some photos do not show a related entry but if I go to the entry where I think it might have been used it is still in use. Am I missing something in matching the entries to the assets?

{% set photos = craft.assets.kind('image') %}
{% for photo in photos %}
    <img src="{{ photo.getUrl('square') }}">
    <br>{{ photo.filename }} / {{ photo.folderId }}
        {# Loop throught entries related to this asset #}
        {% for entry in craft.entries.relatedTo(photo).order('title') %}
            <li>{{ entry.title }}</li>
        {% endfor %}
{% endfor %}

I have tried using the assetusage plugin but it doesn't seem to work with non images and I also wanted to test if it was working properly. I also looked at the Asset-Use plugin but that is beta and only does images.

1 Answer 1


Create this function in your plugins variable:

public function getAllIds(){
    return craft()->db->createCommand()->select('id')->from('elements')->where([
        'not like', 'type', 'Asset'

You'll fetch all ids in Craft, then you can to this:

{% set allIds = craft.your-plugin-handle.getAllIds() %}

{% set usedAssets = craft.assets({
    relatedTo: allIds,
    limit: null,
}).ids() %}

{% set unusedAssets = craft.assets({
    id: 'and, not ' ~ usedAssets|join(', not '),
    limit: null
}) %}

To be honest I'm not sure what the error is in your code. You should get all entries related to the asset, even if they are in a matrix block. Maybe you related to asset to a category and this category to an entry and you assume to get the entry(?)

  • Thanks Robin, but I was trying to do it in a template rather than a plugin. I have also now realised that all of my document links are in a rich text field so not searchable anyway. I'm testing the Asset-use plugin and it looks like it's working OK, I'm just a bit put off by the Beta label.
    – Paul Frost
    Oct 22, 2017 at 16:08

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.