I need to insert Small, thumbnail and swatch roles to all existing product images, any solution? Thanks
1 Answer
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.
-
Mohit Patel, this code replaced all my images with the default image. :)– RobinioCommented 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– JorgBCommented Apr 17 at 10:11