Hello Magento Friends,
In today’s blog, I will provide the solution to remove specific product images programmatically in Magento 2.
Managing product images is a critical part of maintaining a professional and user-friendly e-commerce store. In Magento 2, you might encounter situations where you need to remove specific product images programmatically. Whether you’re updating your product catalog or cleaning up redundant images, this guide will show you how to do it efficiently.
Also read – How to Get Product Images Programmatically in Magento 2
Steps to Remove Specific Product Images Programmatically in Magento 2:
Step 1: Create a file in your Magento root directory at the below path
magento_root_directory\removeProductImages.php
Add the code as given below
<?php use Magento\Framework\AppInterface; try { require '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $productRepository = $objectManager->get("Magento\Catalog\Api\ProductRepositoryInterface"); $productFactory = $objectManager->get("Magento\Catalog\Model\ProductFactory"); $productId = 1; //Enter Your productId here $product = $productFactory->create(); $existingMediaGalleryEntries = $product->load($productId)->getMediaGalleryEntries(); foreach ($existingMediaGalleryEntries as $key => $entry) { unset($existingMediaGalleryEntries[$key]); } $product->setMediaGalleryEntries($existingMediaGalleryEntries); $productRepository->save($product); echo "Images removed successfully for productId = ".$productId; } catch(\Exception $e) { print_r($e->getMessage()); }
Conclusion:
Follow the above method to remove specific product images programmatically in Magento 2. This approach helps you manage your product images dynamically, ensuring your product catalog remains up-to-date and clutter-free.
If you have any queries, let me know through the comment section. Share the tutorial with your friends and stay updated with us for more such Magento 2 solutions.
Happy Coding!