3

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?

4

This should work

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

// 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);
craft()->assets->deleteFiles($unUsedCriteria->ids());
4
  • Thank you, but for some reason, it returns all assets. (I replaced the delete part by a var_dump)
    – r-ninja
    Nov 7 '17 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 Nov 7 '17 at 18:09
  • Does this also cover assets linked in redactor fields? Nov 9 '17 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 Nov 9 '17 at 15:15

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.