2016-09-01 5 views
2

Magento 2で製品イメージを削除しようとしていますが、Magento 1でどのように行うかは非常に異なります。ここでMagento 2で製品イメージを削除する方法

は、私は、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']); 
} 

誰もがこれを実現する方法を知っていますか?

答えて

3

ここでは、製品から画像を削除する方法を学習します。

$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。 http://webkul.com/blog/magento2-programmatically-remove-existing-images-and-add-new-image-to-product/

関連する問題