以编程方式向产品Magento2添加/删除图像

时间:2016-10-26 10:05:13

标签: magento2 magento-2.0 magento-2.0.7

我在以编程方式向产品添加/删除图像时遇到问题。

1 个答案:

答案 0 :(得分:5)

使用以下代码在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();