HummingbirdUK main logo

Coding solutions to business problems

About us

We use code to create solutions to business challenges, bottle-necks and headaches.

If you think your business has a problem that can be solved through code, we are happy to chat things through without any obligation.

Get in touch

Batch remove images from products in Magento

Home / Blog / Batch remove images from products in Magento

Written by Giles Bennett

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 :

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.

Author : Giles Bennett

About the author

Giles Bennett built his first website in 1996, and is old enough to miss Netscape Navigator. Initially a lawyer, he jumped ship to IT in 2008, and after 5 years as a freelancer, he founded HummingbirdUK in 2013. He can be reached by email at giles@hummingbirduk.com.