0

I need to insert Small, thumbnail and swatch roles to all existing product images, any solution? Thanks enter image description here

1

1 Answer 1

1

Paste below code script in pub folder and try in your project.

<?php
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\State;
 
require __DIR__ . '/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
 
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(State::class);
$state->setAreaCode('global');

$dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
$mediaPath = $directory->getPath('media');
$imageType = ['image', 'small_image', 'thumbnail', 'swatch_image']; //this is for all images

if ($collection->getSize()) {
    foreach ($collection as $product) {
        $count = 0;
        $galleryReadHandler = $objectManager->get('Magento\Catalog\Model\Product\Gallery\ReadHandler');
        $galleryReadHandler->execute($product);
        $images = $product->getMediaGalleryImages();
        $productFirstImage = '';
        foreach ($images as $image) {
            if ($count == 0) {
                $productFirstImage = $mediaPath."/catalog/product".$image->getFile();
            }
            $count ++;
        }
        if ($product->getId()) {
            if (file_exists($productFirstImage)) {
                $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
                $product->addImageToMediaGallery($productFirstImage, $imageType, true);
                $product->save();
            }
        }
    }
}

Above code I tested and working fine.

Let me know if any query.

THANKS.

2
  • Mohit Patel, this code replaced all my images with the default image. :)
    – Robinio
    Commented Mar 15, 2023 at 11:42
  • @Robinio Did you solve this? I think it could be because path is wrong it should be "/catalog/product/" instead of "/catalog/product" see the last slash
    – JorgB
    Commented Apr 17 at 10:11

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.