Batch remove images from products in Magento

After a slightly botched image upload attempt which left duplicate images on certain products, a client wanted to start again on the image-front by removing all the images from the products. So a nice easy way to do this programmatically had to be found – and here it is :

Batch Removing Product Images in Magento


Start off with the usual gubbins :

<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

Then load into $products the products that we want to use. In this case we were dealing with a batch of the most recent products uploaded, so we were looking for those products with an ID greater than 14000 :

$products = Mage::getModel('catalog/product')->getCollection()
	->addAttributeToFilter('entity_id', array('gt' => 14000));

The Media API is going to do the hard work for us :

$mediaApi = Mage::getModel("catalog/product_attribute_media_api");

So then loop through each product, get its ID, load the product, load its media items, and if it has any, get the ID of each media item associated with it and delete it – that’s all there is to it :

foreach($products as $product) {
	$prodID = $product->getId();
	$_product = Mage::getModel('catalog/product')->load($prodID);
	$items = $mediaApi->items($_product->getId());
	if (count($items) > 0) { 
		foreach($items as $item) {
			$mediaApi->remove($_product->getId(), $item['file']);
		}
		echo $product->getId() . " done \n";
	} else { 
		echo $product->getId() . " has no images \n";
	}
}

And then finish off…

?>

And there you have it. If you have a lot of images to deal with, probably best to call this from a cron job.