Add/remove image programmatically to product Magento2

后端 未结 1 1421
抹茶落季
抹茶落季 2021-02-10 13:46

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

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-10 14:50

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

    0 讨论(0)
提交回复
热议问题