Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Monday, June 24, 2013

Magento: Remove unused product images in media/catalog/product by product ID

When you delete the Magento products, the gallery images of product are still in the folder /media/catalog/product/. It causes your server getting more disk space because there will have many unused images. To remove all gallery images of a product. Please follow the below code
01
02
03
04
05
06
07
08
09
10
11
12
13
$product = Mage::getModel('catalog/product')->load($productId);
 
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($product->getEntityTypeId(), 'media_gallery');
 
$gallery = $product->getMediaGalleryImages();
echo count($gallery);
foreach ($gallery as $image) {
    $removeFile = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.DS.$image->getFile();
    @unlink($removeFile);
}
 
//$product->save();
$product->delete();
Checked at
  • Magento 1.7.0

2 comments:

  1. Hi,

    For Magento2 here is the solution http://shreejiinfosys.co.in/index.php/delete-unused-images-magento-reg-2.html

    ReplyDelete
  2. I used this code for my Magento store but I was getting a database error. Now I have migrated to Magento 2 and instead of using code, I used an extension by FME which worked smoothly. I will recommend it to any Magento 2 merchant who wants to improve their store performance. Here is the link: https://www.fmeextensions.com/magento-2-image-clean-extension-delete-unused-images.html

    ReplyDelete