繁体   English   中英

如何在Magento 2中删除产品图像

[英]How to remove product images in Magento 2

我正在尝试删除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']);
}

有人知道如何做到这一点吗?

在这里,我们学习如何从产品中删除图像。

$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();

参考。 https://webkul.com/blog/remove-existing-images-and-add-new-image-to-magento-product-programmatically/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM