Main Content

Cleaning Up Your WordPress Media Library

Two folders, one messy and full. The second organized and slim

If you’ve been running a WordPress site for a while, you’ve probably noticed your media library has gotten messy. Since WordPress doesn’t automatically delete media files when you delete the posts they’re attached to, it can grow and grow. Over time, this leaves you with hundreds or thousands of unattached files cluttering your library.

In theory, cleaning these up sounds easy. In practice, it’s risky on larger sites because you can’t easily tell what’s actually being used. Delete the wrong file and you could break something on your site.

I ran into this problem with one of my own sites. I was planning to migrate hosts, so I decided it was a perfect time to do some serious cleanup. The site had thousands of posts and a massive media library, and I wanted to remove over 8000 low-quality posts along with their associated files. Since WordPress doesn’t have a built-in way to do this safely, I wrote a couple of custom plugins.

The first plugin, Attach Orphaned Images, searches through unattached images and checks if they’re actually being used anywhere. If they are, it automatically attaches them to the correct content. In just a few minutes, it scanned and attached over 3000 images.

The second plugin, Delete Attached Media on Post Deletion, inserts itself when you delete posts. When you permanently delete a post, instead of leaving the media behind, it grabs any files attached to that post, verifies they’re not used elsewhere on the site, and then deletes them. Since verification takes time, this runs as a background process.

Between these two plugins, I was able to clean up the site and free up a significant amount of disk space. The solution wasn’t perfect, and I still had to do some manual cleanup afterward, but the plugins handled the heavy lifting.

The process did take time. The plugins try to do things in batches to keep from overloading the server, and the verification step added hours to the timeline. Most of that was automated, though, just a cron job running in the background.

In the end, I reduced the media library by three quarters. That kind of cleanup makes all the effort worth it.

If you’re trying to clean up your WordPress media library, take a look at my plugins and see if they’ll work for you. And, as always, backup your site before running the plugins, just in case.


Leave a Reply