Magento 2 delete unused product images
There are many modules and scripts to delete unused product images in Magento 2.
However, sometimes trying to keep away from installing new modules is not a bad idea. Every module introduces a certain risk and requires backup before you attempt to install it.
Now we will go through how to delete unnecessary images:
- Export all products. System -> Export. Select products from the drop down. Do not select any fields and just press Continue.
- Make a backup of the files and DB
- Test the products table that we just exported. Go to: System -> Import. Select Products, Add/Update. Select field enclosure. Select the file you just downloaded and press Check Data ( Do not proceed to actual import ).
- Move images -> pub/media/catalog/product folder to /var/importexport. At this point the product images will be gone from the site
- Now if you have many products it is a good idea to split the CSV file in few. We split the file in 500 products and worked fine.
- Delete entries from Table `catalog_product_entity_media_gallery` that do not have a corresponding entry in catalog_product_entity_varchar.
- DELETE FROM `catalog_product_entity_media_gallery` WHERE value NOT IN (SELECT b.value FROM `catalog_product_entity_varchar` b WHERE b.value IS NOT NULL
- Once again Select System -> Import. Select Products, Add/Update. Select field enclosure. Select the file you just downloaded. In Images File Directory write the path to the moved images folder var/importexport/product
- Run command bin/magento catalog:images:resize
Another way to delete unused images is using a module. Here is one that you can use. It is not risk free, so do a backup first