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

以编程方式向产品Magento2添加/删除图像,magento2,magento-2.0,magento-2.0.7,Magento2,Magento 2.0,Magento 2.0.7,我面临着以编程方式向产品添加/删除图像的问题。使用以下代码在Magento2中向产品添加/删除图像 // Instance of object manager $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); *Remove Images From Product*/ $productId = ; // Id of product $product = $objectManager->create(

我面临着以编程方式向产品添加/删除图像的问题。

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

好的,我将尝试根据上述代码进行更改。感谢您的回复。我正在尝试此解决方案我的图像删除效果良好,图像添加也很好,但它未设置为基小缩略图$attributeImage=array('image','small_image','thumbnail')$product=Mage::getModel('catalog/product')->load($product\u id);$product->AddImageToDiagallery($file,$attributeImage,true,false)$产品->保存();请尝试这个,它可能会帮助你。我使用了相同的代码,当只有一个商店视图时,它工作正常。但是如果我们有多个商店视图,那么它就无法删除图像。如何获取图像路径?