0

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 ?

0

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:

$gallery = $_product->getMediaGalleryImages();
if (count($gallery) > 0) {
foreach($gallery as $image){
$this->productGallery->deleteGallery($image->getValueId());
}
$_product->setMediaGalleryEntries([]);
$_product->save();
}

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/

2
  • Adding additional $product->save(); after saving productRepository solves all problems. Thanks!
    – Matthias
    Nov 29 '21 at 8:25
  • Glad to hear your problem was solved.
    – Amit Saini
    Nov 30 '21 at 10:06
0

This will help you to resolve the issue https://www.mageplaza.com/devdocs/add-images-to-product-programmatically-magento-2.html

it's working well i verified this on my local :)

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.