dq1230123 2016-09-01 00:24
浏览 29

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

I'm trying to remove product images in Magento 2, but all I can find is how to do it in Magento 1, which is very different.

Here is what I found for 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']);
}

Anyone know how to accomplish this?

  • 写回答

1条回答 默认 最新

  • douhuzhi0907 2016-09-03 11:33
    关注

    Here we learn how to remove images from product.

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

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

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向