Heii new to Magento I have product with same images for multiple products but after i upload products via csv it creates seprate image directory for the products in var/cache/

Not a developer but it's the only problem I can't solve

1 Answer 1


You just need to create one root file and paste below code in that file and run file in browser OR you can create one custom module and apply this code for one image assign to multiple products.

This code help to you.

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

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$imagePath = $dir->getPath('media')."/yourimage.jpg"; // Your image should be on pub/media path
$imageType = ['image', 'small_image', 'thumbnail'];

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);

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.