How to delete images of product in Magento after product delete programmatically...?

1.3k views Asked by At

I used below code to delete a product from Magento Database programmatically and this code works for me.

  $productEntityTable = Mage::getModel('importexport/import_proxy_product_resource')->getEntityTable();
  if ($idToDelete) {
  $this->db->query("DELETE FROM `{$productEntityTable}` WHERE `entity_id` IN (?)", $idToDelete);
  echo 'Deleted';
  }

But I want to delete product images also and for this, I used below piece of code

$_product = Mage::getModel('catalog/product')->load($idToDelete);
$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');
}

And I got following error and I Used many code but all the time I got the same error.

Fatal error: Call to a member function getUserId() on a non-object in /my_path/app/code/local/Mage/Catalog/Model/Product/Attribute/Backend/Media.php on line 263

2

There are 2 answers

1
Murtuza Zabuawala On

May its asking for current user.

set current user as admin for this add below line top of the code

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
3
faizanbeg On
    Use can use below code

<?php
    require_once "YOURMAGENTODIR/app/Mage.php";
    umask(0);
    Mage::app('admin');
    Mage::setIsDeveloperMode(true);

    $productCollection=Mage::getResourceModel('catalog/product_collection');
    foreach($productCollection as $product){
    echo $product->getId();
    echo "<br/>";
             $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
            echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
    echo "<br/>";

    $MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
    echo "<pre>";
    print_r($MediaGallery);
    echo "</pre>";

        foreach($MediaGallery as $eachImge){
            $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
            $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
            $DirImagePath=str_replace("/",DS,$eachImge['file']);
            $DirImagePath=$DirImagePath;
            // remove file from Dir

            $io     = new Varien_Io_File();
             $io->rm($MediaCatalogDir.$DirImagePath);

            $remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
        }


    }