I've built an image importer (due to some custom requirements on image name matching SKUs) and in it, I delete all of a product's existing images before importing new ones. My code looks like this:
/* @var $mediaApi Mage_Catalog_Model_Product_Attribute_Media_Api */
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach ($items as $item) {
$mediaApi->remove($product->getId(), $item['file']);
}
This calls Mage_Catalog_Model_Product_Attribute_Media_Api::remove()
which looks like this:
/**
* Remove image from product
*
* @param int|string $productId
* @param string $file
* @return boolean
*/
public function remove($productId, $file, $identifierType = null)
{
$product = $this->_initProduct($productId, null, $identifierType);
$gallery = $this->_getGalleryAttribute($product);
if (!$gallery->getBackend()->getImage($product, $file)) {
$this->_fault('not_exists');
}
$gallery->getBackend()->removeImage($product, $file);
try {
$product->save();
} catch (Mage_Core_Exception $e) {
$this->_fault('not_removed', $e->getMessage());
}
return true;
}
The line $gallery->getBackend()->removeImage($product, $file);
suggests that it deletes the image file, but if you look at Mage_Catalog_Model_Product_Attribute_Backend_Media::removeImage()
you'll see that it doesn't:
/**
* Remove image from gallery
*
* @param Mage_Catalog_Model_Product $product
* @param string $file
* @return Mage_Catalog_Model_Product_Attribute_Backend_Media
*/
public function removeImage(Mage_Catalog_Model_Product $product, $file)
{
$attrCode = $this->getAttribute()->getAttributeCode();
$mediaGalleryData = $product->getData($attrCode);
if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
return $this;
}
foreach ($mediaGalleryData['images'] as &$image) {
if ($image['file'] == $file) {
$image['removed'] = 1;
}
}
$product->setData($attrCode, $mediaGalleryData);
return $this;
}
Two questions:
- Is there any normal Magento situation where a product's image is used in more than one place? (The CMS and WYSIWYG image tools don't let you link to product images that I know of.)
- Before I go building a custom solution to delete unused images from the media directory, I want to make sure: Should I be expecting Magento to delete these images for me? From the code that I can find, it doesn't attempt to do that.