Add/remove image programmatically to product Magento2

僤鯓⒐⒋嵵緔 提交于 2019-12-21 02:47:08

问题


I am facing problem to add/remove image to product programmatically.


回答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();


来源:https://stackoverflow.com/questions/40259303/add-remove-image-programmatically-to-product-magento2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!