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?
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityThe 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?
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());
.find()
with an .ids()
I updated my answer. It works now for all assets with no relation
Nov 7, 2017 at 18:09