Delete images not used in WordPress

and find unused images first!

Delete images not used in WordPress

If your website is more than few months old you know how surprisingly large your wp-content/uploads can become one day. You don’t know where all that stuff comes from and where it goes but it just occupies all free space on your web server.

This post will help you define useless media correctly and get rid of it. Just watch out what you are doing as delete means delete.

Case 1: all images on your site are stored as WP attachments

Good media: all WordPress attachments

Bad media: anything stored in  uploads directory that is not WP attachment

This function will free up disk space on your hosting account. It will scan your wp-content/uploads directory (recursively) and check every found file whether it is WP attachment or not. All files that are not WP attachments will be deleted. If you got rather large uploads folder (say 5 gb) you might want to split process into parts by folders.  I’ve got 1Gb checked and cleaned in 15 seconds (only 300 MB left!).

This is how we find and delete images which are not attachments.

But what if your images are not stored as WP attachments at all but are still used on your website?

Case 2: images on your site are uploaded through custom fields and are not stored as WP attachments

Good media: all images saved in specified custom fields

Bad media: anything else in uploads directory

  1. Define all good images
    First, we need to get the combined list of all «good» images that are used on the website, so later we can delete all files that are not used.

    I’ll show one of the cases as an example. It’s online bookstore.

    We’ve managed to get rid of 32 thousands of useless files and free up to 75% of disk space on web server. 

    Before: 42096 images 4767 MB
    After: 9202 images 1251 MB
    Cleaned 32894 images and saved 3516 MB disk space

    Here we’ve got 3 post types: posts (used for books), bookauthor and booklist. Image for every post type is stored in separate custom field (book cover, author’s pic and book list image). We’ll obtain the list of images used for each CPT and combine them together to get full list of good images. These are the images that we will preserve.

  2. Delete images not used in WordPress
    So we’ve got the complete list of good images that are used on the website in variable $all_good_pictures. Now we’ll  go through the wp-content/uploads directory and check every file whether it’s on list or not. If it’s not listed we’ll just delete it.

Here is how we can get our WordPress install clean and well-organized, reduce data amount and CPU load and even move to cheaper hosting plan as we won’t store gigabytes of trash anymore.

Just in case, you’ve got backup, right? 😉

 

Delete images not used in WordPress: 2 комментария

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *