The title is self-explanatory, but I need to buid a service function to remove unused assets, or at least to fetch those in order to delete found assets after.

Any simple solution?

1 Answer 1


This should work

//First fetch all ids from elements table
$allIds = craft()->db->createCommand()->select('id')->from('elements')->where([
    'not like', 'type', 'Asset'

// query for all related Assets -> assets that are used somewhere
$usedAssetCriteria = craft()->elements->getCriteria(ElementType::Asset);
$usedAssetCriteria->relatedTo = $allIds;
$usedAssetCriteria->limit = null;
$usedAssets = $usedAssetCriteria->ids();

// query for all assets not in the list of the used one
$unUsedCriteria = craft()->elements->getCriteria(ElementType::Asset);
$unUsedCriteria->id = 'and, not ' . implode(', not ', $usedAssets);
  • Thank you, but for some reason, it returns all assets. (I replaced the delete part by a var_dump)
    – r-ninja
    Commented Nov 7, 2017 at 17:54
  • 2
    sry, my mistake, you have to replace the .find() with an .ids() I updated my answer. It works now for all assets with no relation Commented Nov 7, 2017 at 18:09
  • Does this also cover assets linked in redactor fields? Commented Nov 9, 2017 at 15:09
  • No, that's only one reason why you should avoid using images in rich text fields. The advantage of craft is: you can avoid using images in those fields and instead create a matrix element with a text and image input. However, if you want include those you would have to loop through every rich text in every field (including matrix elements) and parse the images Commented Nov 9, 2017 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.