magento2: Can't add product images roles with $product->addImageToMediaGallery

I tried To Upload Images by using

 $imagePath = $mediapath."image_upload/tmp/products/".$value['image_path'];// path of the image
 $product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail', 'swatch_image'], true, false);

Images are uploded success, but Images roles are not assign to this uploded Image

image

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Comments: 34 (4 by maintainers)

Most upvoted comments

Facing same issue with version 2.4.6 @engcom-Hotel

I also had issues importing images with proper roles. I figured out the product must be loaded again after it was saved with the ProductRepositoryInterface - otherwise the image is saved but the roles are set to “no_selection”:

//Remove images first before adding new ones
$product = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$product->setMediaGalleryEntries([]);

$productInterface = $this->_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$productInterface->save($product);

// Reload product and add media image
$imagePath = "import/imagename.jpg";
$product = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$product->addImageToMediaGallery($imagePath, ['image', 'thumbnail', 'small_image'], false, false);
$product->save();

Hope this helps someone.