I am updating the product from the frontend and I want to only remove specific images which client is deleted not all the images.
Is there any method available ?
help will be appreciated.
asked Oct 13, 2019 at 6:52
-
this link will help you: magento.stackexchange.com/questions/139616/…Sangeeta Chandaliya– Sangeeta Chandaliya2019年10月14日 04:58:08 +00:00Commented Oct 14, 2019 at 4:58
1 Answer 1
Use following code to add/remove image from product in Magento2.
// Instance of object manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
*Remove Images From Product*/
$productId = ; // 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);
/*Add Images To The Product*/
$imagePath = "sample.png"; // path of the image
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();
answered Oct 14, 2019 at 4:59
default