0

I am creating products programmatically. I am using below code to add product image.. Images are adding perfectly fine.. but image roles are not showing. Can anyone please help me to add image roles in product images programmatically.

$c_product = $ob->create('Magento\Catalog\Model\Product')->load($product->getId());
if(file_exists($image1))
    $c_product->addImageToMediaGallery($image1, array('image', 'small_image', 'thumbnail'), false, false);   
9
  • What result come in $image1 varriable ? Feb 21 '18 at 10:59
  • it gives image path. Image is adding in product.. image role is not showing.. that's my issue..
    – Keerthana
    Feb 21 '18 at 11:04
  • yes - try with this $c_product->addImageToMediaGallery( $dir->getPath('media').$image1, null, false, false ); Feb 21 '18 at 11:06
  • I'm amused how adding images with addImageToMediaGallery is working for you. I had to do work arounds for it to work. Feb 21 '18 at 11:06
  • By the way do the images roles already exist? Feb 21 '18 at 11:07
0
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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.