I need to insert Small, thumbnail and swatch roles to all existing product images, any solution? Thanks
2 Answers
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.
Backup your Magento store database and files before making any changes.
Create a script that will loop through all products and their images and add the necessary roles.
Here's the script
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$productCollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$products = $productCollection->create();
foreach ($products as $product) {
$productImages = $product->getMediaGalleryImages();
foreach ($productImages as $image) {
$image->setTypes(['small_image', 'thumbnail', 'swatch_image']);
$image->save();
}
}
Save the script in your Magento root directory.
Run the script via the command line or by accessing it via a URL in your browser.
Once the script is finished running, clear Magento cache and reindex as necessary.
-
Harun
$product Images = $product->getMedia Gallery Images()
returns data but is not included of the loop– RobinioMar 15 at 11:46 -