我试图在Magento 2中删除产品图片,但我能找到的是如何在Magento 1中完成,这是非常不同的。
以下是我为Magento 1发现的内容:
if ($product->getId()){
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach($items as $item)
$mediaApi->remove($product->getId(), $item['file']);
}
任何人都知道如何做到这一点?
答案 0 :(得分:3)
在这里,我们将学习如何从产品中删除图像。
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
/*Remove Images From Product*/
$productId = 100; // 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();