1

I want to change bulk product image base image programmatically Magento 2

0

1 Answer 1

1

Please make changes as per your requirement in below script and run script from root

<?php
ini_set('memory_limit', '512M');
set_time_limit(0);
require __DIR__ . '/app/bootstrap.php';
$bootstrap     = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create(); // you can load product collection as per your requirement here 
$imagePath = $dir->getPath('media')."/yourimage.jpg"; // Your image should be on pub/media path
$imageType = ['image']; //this is only for base image
// $imageType = ['image', 'small_image', 'thumbnail']; //this is for all images

if($collection->getSize()) {
    foreach ($collection as $product) {
        if($product->getId()) {
            if(file_exists($imagePath)) {
                $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
                $product->addImageToMediaGallery($imagePath, $imageType, false, false);
                $product->save();
            }
        }
    }
} 

Hope this will help you!

4
  • How to set product base image from existing product images programmatically ? Dec 7, 2019 at 9:51
  • $product->getMediaGalleryImages() using this function get product images inside collection and set image path in $product->addImageToMediaGallery() function Dec 7, 2019 at 10:04
  • Is it possible to set product image position ? Dec 7, 2019 at 10:35
  • $product->getMediaGalleryImages() using this function get product images inside collection and set image path in $product->addImageToMediaGallery() function Please share reference Dec 8, 2019 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.