Deleting product images when a resource is deleted

Hi all!

I have created a small MODX site which sells one off pieces of second hand clothing.
I’ve noticed that over the past six months, the server is filling up with product images!
Each product has a number of iages added across a few TVs.

Is there a way of removing the physical files associated with a resource when the resource is deleted?

The problem is the user isn’t naming the images, so it’s impossible to know what can be removed and what can’t!

What I was wondering was whether there was a way to automatically create a directory with a name of the ID of the resource when an image is uploaded. and then when the resource is deleted, it deletes the directory (and contents) of the same name as the resource ID.

I don’t even know where to begin, but thought it was an interesting challenge which other users may benefit from when housekeeping a large turnover of images.

Thanks in advance for any pointers!


I suppose you could create a plugin that runs on the event OnBeforeEmptyTrash, then loops through all the resources that are about to be deleted, reads the values of their image-TVs and deletes these image files.

With MIGX there is such a functionality:

How are images added/uploaded on your site? In the manager? On the frontend?

Hi there, first I think you’ll need to setupo the folder and some sort of identifier for a newly crated resource, here is some info on catching the new resource event then do something similar on resourceDeletion, I think you could store the folder info as a TV, the just delete it when the OnResourceDelete or OnBeforeEmptyTrash as @ halftrainedharry pointed, it really depends on your business rules

Thanks Harry. The images are uploaded in the backend via a single image TV for the primary image, and also via migx with additional images (if there are any).
I guess i could do it all via Migx if need be - it’s just some products only have one image, so I have that setup as a ‘primary image’ TV.

All the images go into a dedicated media source.

thanks - I will have a read!

1 Like