Magento programmatically remove product images

user439441 picture user439441 · Apr 19, 2011 · Viewed 51.6k times · Source

This must be a such a simple programming task that I absolutely cannot find any information about it on the net. Basically, I'm trying to DELETE product images. I want to delete all images from a product's media gallery. Can I do this without wading through a million lines of code for such a simple task?

Please note that I've already tried this:

$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
    $gallery = $attributes['media_gallery'];
    $galleryData = $product->getMediaGallery();//this returns NULL

    foreach($galleryData['images'] as $image){
        if ($gallery->getBackend()->getImage($product, $image['file'])) {
            $gallery->getBackend()->removeImage($product, $image['file']);
        }
    }
}

This absolutely does not work. I'm trying to delete images during an import so that I do not keep accruing duplicates. Any help would be greatly appreciated.

Answer

user439441 picture user439441 · Apr 19, 2011

Okay, this is how I finally fixed my problem.

if ($product->getId()){
    $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
    $items = $mediaApi->items($product->getId());
    foreach($items as $item)
        $mediaApi->remove($product->getId(), $item['file']);
}

This is the link that finally set my head straight: http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product_attribute_media

Too bad it's not as simple as $product->getImages(), eh?