Programmatically add multiple images magento 2

This tutorial explains how to programmatically add multiple images Magento 2. The additional images urls are reading from the CSV. I have downloaded the additional images from the remote directory.

Please also refer other tutorials which explain how to download images from remote url and programmatically add multiple images magento 1.

Programmatically add multiple images magento 2

Add Images Product Gallery

The below code reads the image URLs from the CSV and assigned the images to the existing products.

function importAddImages($prodDatas, $_objectManager, $prdbasepath, $newProductIds) {

    foreach($prodDatas as $prodData) {

        if(isset($newProductIds[$prodData[2]])) {
            /* Get new product Id*/
            $newProdId = $newProductIds[$prodData[2]];
            echo 'New Product Id '.$newProdId.' - '.$prodData[2].PHP_EOL;
            $imgs = explode('|',$prodData[10]);
            
            if(sizeof($imgs) > 1) {
                /* Assign additional images to existing products */
                $product = $_objectManager->create('Magento\Catalog\Model\Product')->load($newProdId);
                $productRepository = $_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
                $productRepository->save($product);

                for ( $i=1; $i << sizeof($imgs); $i++ ) {
                    
                    echo 'Add Images :' . $prdbasepath.basename(trim($imgs[$i])) . PHP_EOL;
                    $image_directory = $prdbasepath.'data'.DS.basename(trim($imgs[$i]));

                    if (file_exists($image_directory) && getimagesize($image_directory)) {

                        echo 'File exists'.PHP_EOL;
                        $product->addImageToMediaGallery($image_directory, array('image', 'small_image', 'thumbnail'), false, false);
                        $product->save();

                    }
                }

            }

        }
    }

    /*Add Images To The Product*/

}

Initialise Object Manager and set file path

As the first step initialize object manager and set the file path.

define('DS', DIRECTORY_SEPARATOR);

use \Magento\Framework\App\Bootstrap;

include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$_objectManager = $bootstrap->getObjectManager();
$app_state = $_objectManager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');
$filespath = $_objectManager->get('\Magento\Framework\Filesystem');
$prdbasepath = $filespath->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*