0

I have followed few blogs to add and remove media gallery images but not able to set gallery images as per store wise programmatically.

https://www.siphor.com/adding-and-removing-media-images-programmatically-in-magento-2/ http://leftcurlybracket.com/update-product-image-programmatically/

Can anyone help me with above?

0

Please check the below code.

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

May be it will help you.

Thanks

2
  • 1
    Hi Mayur, Thanks for your reply. We need to set media gallery image store wise as your code only set media gallery images in all store views. Oct 4 '20 at 14:05
  • Ok @SanjayJethva I will check if any new code I will find then will give you here. Oct 5 '20 at 3:58
0

You can upload a product image to a specific store view by setting the store ID in the product object before calling the addImageToMediaGallery.

Check this code e.g.

$product->setStoreId($storeId);

// Add image to media gallery
$product->addImageToMediaGallery(
    $productMediaFile,
    [
        'image',
        'small_image',
        'thumbnail'
    ],
    false,
    false
);
$this->productRepository->save($product);

If you want to upload in several store views, you may need to hide the previously uploaded image from other store view so that it won't show in the specific store view.

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.