From time to time you might want to remove images from a large amound of products in Magento. I had this exact situation recently trying to help someone in the Magento IRC channel (#magento).
In our case, we needed to go through all configurable products and remove the images for the simple products associated with them. Obviously this would be very time consuming to do by hand, so I put together a PHP script to do it for me.
Here is the code to remove the images (media gallery) for an individual product:
1 2 3 4 5 6 7 8 9 10 11 |
$_product = Mage::getModel('catalog/product')->load('1234'); $mediaApi = Mage::getModel("catalog/product_attribute_media_api"); try { $items = $mediaApi->items($_product->getId()); foreach($items as $item) { echo ($mediaApi->remove($_product->getId(), $item['file'])); } } catch (Exception $exception){ var_dump($exception); die('Exception Thrown'); } |
Note: There is actually no need for the first line. If you know the ID, that’s all the Media API needs to work. You don’t need to load the product object – it’s just assumed you probably already did. In theory, this could work from a CSV of product IDs.
Image Credit: Stuck in Customs via photopin
Comment or tweet @douglasradburn