We often delete a product which is sold out, and we never sell it in the future, we usually delete this product right away to save our web hosting and let the web hosting run faster. But by default, when we delete a product from Magento 2.3 or Magento 2.4. Its related product images will not be removed. How to delete the related useless product images then? Say, at https://www.prescriptionsafetyglassescanada.com/ , a month ago, there are 400 products which we do not sell anymore, and we have deleted these products already. But there are at least 2GB of related product images that are still at our hosting. Here let me share the skills on how to delete these images without installing the third Magento Modules. All by command lines!
cd /home/wwwroot/prescriptionsafetyglassescanada.com/pub/media/catalog
/pub/media/catalog# du -hsx * | sort -rh | head -10
3.7G product
6.7M category
200K tmp
There are 3.7 product images. After we deleted all useless product images, there are only 700M images under /home/wwwroot/prescriptionsafetyglassescanada.com/pub/media/catalog/prodcut
Step A, find out the useless product images list from the database:
Showing rows 0 – 2681 (2682 total, Query took 0.0055 seconds.)
There are 2681 images that are useless.
Export the list to a .CSV file.
Delete all columns expert “value” column,
Delete the first line, which content is “value”.
Sometimes we may find that we can not use PhpMyAdmin to export the data, you can try adminer.php.
Export and paste the data to Sublime, and delete the first line, which content is “value”.
Sample data:
/d/s/dsc1.jpg
/d/s/dsc2.jpg
/d/s/dsc3.jpg
/d/s/dsc4.jpg
/d/s/ds1.jpg
Add rm -rf . before each line of the data and let them be:
rm .rf ./d/s/dsc1.jpg
rm .rf ./d/s/dsc2.jpg
rm .rf ./d/s/dsc3.jpg
rm .rf ./d/s/dsc4.jpg
rm .rf ./d/s/ds1.jpg
How to do so?
First, select all lines: Ctrl + A
Second, locate the cursor at the end of each line: Ctrl + Shift + L
Last, move the cursor up one line, now the cursors are at the beginning of each line.
Add “rm -rf .” to each line. Done.
Use ssh to connect your web hosting, and go to /home/wwwroot/prescriptionsafetyglassescanada.com/pub/media/catalog
Copy all lines and run the commands to delete the useless images.
End.