Remove product image in magento2

<?php

use Magento\Framework\App\Bootstrap;

use Magento\Sales\Model\Order;
use Magento\Catalog\Model\Product as ModelProduct;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$obj->get('\Magento\Framework\App\State')->setAreaCode('frontend'); // for remove Area code is not set error
$storeManager = $obj->get('\Magento\Store\Model\StoreManagerInterface');
$baseUrl = $storeManager->getStore()->getBaseUrl();
$string = 'CC103,CC107,CC118,CC119,CC120,CC121,CC126,CC129,CC130,CC131,CC132,CC122_9IN1,CC124,';
$productArray = explode(",", $string);

//Instance of object manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
foreach($productArray as $sku)
{    
$products = $objectManager->create('Magento\Catalog\Model\Product')->loadByAttribute('sku', $sku);
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($products->getId());
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry)
{
    unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$productRepository->save($product);

echo "Product Image has been removed for ".$product->getSku().'=='.$product->getId()."</br>";


}

echo "Yahooooo";

Note : If you have got any error then first you have to check in the Product "URL KEY" if this column is blank, please fill the url key And run the file.

Comments