Magento 1.8 – How to Delete Non-Selected Base Images

imagemagento-1.8

$product1 = Mage::getModel('catalog/product')->loadByAttribute('sku', 'FN244403');
$product2 = Mage::getModel('catalog/product')->loadByAttribute('sku', 'FN229437');
$product1ID = $product1->getId();
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "SELECT * FROM `catalog_product_entity_media_gallery` WHERE `entity_id` = '$product1ID' 

LIMIT 1";
$rows       = $connection->fetchAll($sql);
echo $path = $rows[0]['value'];
   echo "Edited sku is ".$product1->getSku()." ".$product1->getImage()." ".$product1-

>getThumbnail()." ".$product2->getImage();
echo " asdasd ".Mage::getBaseDir('media') . DS . 'catalog/product' .trim($rows[0]['value']);  
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$product1->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'catalog/product' .trim

($rows[0]['value']), array('image', 'small_image', 'thumbnail'), false, false); 
$product1->save(); 

I am add for product image such as Small image, Base image, Thumbnail. How i can delete second lost image wich not select as Small image, Base image, Thumbnail
Thanks

Best Answer

The best way I've found to remove images is to use the product_attribute_media_api model.

$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
try {
    $items = $mediaApi->items($product->getId());
    foreach($items as $item) {
            if ($product->getSmallImage() != $item['file']
                && $product->getThumbnail() != $item['file']
                && $product->getImage() != $item['file']) {
                    $mediaApi->remove($product->getId(), $item['file']);
            }
    }
} catch (Exception $exception){
    var_dump($exception);
    die('Exception Thrown');
}

I've only used this previously to removal ALL images from a product (as in the example above). However, looking at the documentation (http://freegento.com/doc/de/d53/_catalog_2_model_2_product_2_attribute_2_media_2_api_8php-source.html) you should be able to either query the model, or the existing $product object to figure out which ones you want to remove.

Edit: Updated to check against existing files - code not checked.