Perfect pictures encourage more clicks and drive more sales!
As you plan the design of your Magento 2 store, you might think that images are those “nice to have” elements that don’t serve much of a purpose beyond looking good. But images do so much more than paint a pretty picture.
However, to add multiple images to the product at once, you need to add images for each product manually in the default Magento 2. To overcome such manual tasks, you can add images to product gallery in Magento 2 via CSV bulk upload.
With this programmatic method, add multiple images to the product gallery at once and leverage the benefits of having images in an E-commerce store such as:
- Stores with more images get more views
- Images capture attention
- Convenience in online shopping
- Improved SERPs
- Improved click-through rate
- Boost in social media
- Boosts SEO value
Now that you know what you’d miss if you do not fill your product gallery with suitable images, get on implementing the below method!
Method to Add Images to Product Gallery in Magento 2:
Create a new php file in the ROOT directory and place the below code to assign images:
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$importDir = __DIR__ . '/pub/media/catalog/product'; //This is the directory path from where you have to take the images
$i = '12'; // It must be product ID for which product it is to be assigned
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($i);
$id = $product->getId();
$url = $importDir . $product->getImage();
$product->addImageToMediaGallery($url, array('image', 'small_image', 'thumbnail'), true, false);
echo "<br /><br /> $id Product Save Succefully";
If you have any doubts on the topic, please share them in the Comments section below. I’d be happy to help.
I’d be very grateful if you helped share this helpful post on social media to fellow developers!
Get Weekly Updates
Never miss Magento tips, tricks, tutorials, and news.
Thank you for subscribing.
Something went wrong.