During an import of all the new products in the "media gallery" section of each product, a second image path has been added for error.
I want to avoid manually deleting all the second images of each product. Is there a way to automatically delete all the second images of each product without touching the main image with "order: 1"?

Thanks for any help

1 Answer 1


I haven't tested this, but I imagine something like this would work.

$collection = Mage::getModel('catalog/product')->getCollection();
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");

foreach($collection as $product) {
    $product = Mage::getModel('catalog/product')->load($product->getId());
    $entityTypeId = $product->getEntityTypeId();
    $mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
    $gallery = $product->getMediaGalleryImages();
    foreach ($gallery as $image) {
        if($image['position'] != "1") {
            $mediaGalleryAttribute->getBackend()->removeImage($product, $image->getFile());

What I'm doing here is looping through all of the products and then through their images and removing any that do not have a position of 1.

  • Hi, thanks for the reply. I tried your code but it gives me as an error: "Undefined variable: i". Is it possible to create an if in your code? I would like to be able to tell Magento to delete images of products that do not have "order: 1" in the position of media_gallery_position
    – Gabriel91
    Feb 6, 2018 at 15:06
  • Try my updated solution, but back up your work first to be on the safe side! Feb 6, 2018 at 15:22
  • I'm doing the tests locally for now. Anyway I tried your code but nothing has changed for now. I uploaded the code to a php file and uploaded it to the root of the site, also loading Mage.php but nothing happened. Blank page is enough. When I returned to the backend I saw that the second image of the products was always there.
    – Gabriel91
    Feb 6, 2018 at 15:43
  • Try my updated code! I'm not sure why using the media API doesn't work, but this method definitely does. Feb 6, 2018 at 16:01
  • Thanks for your patience. I tried your code again. The page continues to load endlessly, as if it were looped. After 20 minutes i tried to saw in "manage products" and the product has ever the second image.
    – Gabriel91
    Feb 6, 2018 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.