0

I have all product images in one folder. Images are in path like - pub/media/Fotos/MA/{{ sku }}/

So need to import images as per SKU folder. I want dynamic script for it.

1 Answer 1

0

Here i have created one custom script and it is working properly in my case.

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

$storeManager = $obj->get('\Magento\Store\Model\StoreManagerInterface');
$baseUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

$productCollectionFactory = $obj->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');

$mediaAttribute = array('thumbnail','small_image','image');

$fp = fopen('skuimage.csv', 'w');
$csvHeader = array("sku");
fputcsv( $fp, $csvHeader,",");
$k = 1;

foreach($collection as $collec)
{
    $productRepository = $obj->get('\Magento\Catalog\Model\ProductRepository');
    $productObj = $productRepository->get($collec->getSku());

    echo "Count Product->".$k."<-ID->".$collec->getEntityId();

    $productimages = $productObj->getMediaGalleryImages();
    if(count($productimages) > 0) {
        $msg = 'Product has already images. Product ID: ' . $productObj->getId();
        echo $msg . '<br />';
    } else {
        $dirname = BP."/pub/media/Fotos/MA/".$collec->getSku().'/';
        if(is_dir($dirname)) {
            $images = glob($dirname.'*.{jpg,JPG,jpeg,JPEG,png,PNG}',GLOB_BRACE);
            $i = 0;
            foreach ($images as $image) {
                if(file_exists($image)) {
                    echo "file exist";
                    if($i == 0) {
                        $productObj->setStoreId(0);
                        $productObj->addImageToMediaGallery($image, $mediaAttribute, false, false);
                    } else {
                        $productObj->addImageToMediaGallery($image, null, false, false);
                    }
                    try {
                        $productObj->save();
                    } catch(\Exception $e) {
                        echo $e->getMessage();
                        exit;
                    }
                }
                $i++;
            }
            $msg = 'Product image saved. Product ID: ' . $productObj->getId();
        } else {
            fputcsv($fp, array($collec->getSku()), ",");
        }
    }
    $k++;
}
fclose($fp);

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.