Magento – How to delete product images using magento csv import in magento 2

csvmagento-2.1magento2magento2.1.0product-images

Magento Version: 2.1.0

We have added the wrong image for some of the products when importing through Magento CSV import. we want to remove the images from those products and add new images or replace the images for the same.

We are trying to import using the normal Magento import functionality by selecting replace option. If we select to delete it will delete the complete product. Same issue we will get if we want to remove any multiselect option and add new for any particular product.

EX: if SKU is xyz456 – we added 3 images before and we want to remove these and add new 3 or 4 images or replace the images for the same SKU then it is not working. It will add new images also and it will keep old images also.

Same way if we have selected multiselect options for attribute lets say material: wood, iron and we want to change it to steel, copper then it is not allowing. It will add Material: wood, iron, steel, copper

Can anyone please explain how we can update these. Magento has not provided clear documentation on product import and export functionality.

Best Answer

Use following code to remove image from product in Magento2.

// Instance of object manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$productId = Your_Product_Id; // Id of product

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
    unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$productRepository->save($product);
Related Topic