When we update images programmatically, we see correct images in admin, but not in shop frontend.
Correct images are saved to catalog_product_entity_media_gallery.
But magento shop frontend shows still old images.
Also in catalog_product_entity_varchar there are still the old images.
Here is the code we use for delete old images:
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$productRepository->save($product);
and here is the code for uploading the new one:
$product->addImageToMediaGallery($copyFile, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();
Code to see the files:
$objectManager->get("Magento\Catalog\Model\Product\Gallery\ReadHandler")->execute($product);
$productImages = $product->getMediaGalleryImages();
foreach ($productImages as $image) {
print "local= <img src='" . $imageData['url'] . "' /> ";
}
Why does the code change only the admin media gallery, but not the shop frontend images for Magento 2.3.6 ?
Best Answer
Its looks like in your code of remove product gallery images, it's not hit all the required media gallery tables in the database. I suggest you follow the below links for this:
Remove and add gallery images for the product:
https://www.mageplaza.com/devdocs/add-images-to-product-programmatically-magento-2.html
Or for delete gallery images for the product, check below code:
For a better understanding of Product media images DB tables, check the below link:
https://www.rakeshjesadiya.com/how-product-images-are-saved-in-database-magento-2/