Bhaveshpp

Professional Magento Developr - Healp eachother to grow

Magento2: Update product attribute using root script

10 Sep 2021 » magento2
<?php 
echo "<pre>";
print_r("Hello I am here ". __FILE__);
echo "<br/>";

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', -1);
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;

require 'app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/20210910-assign-incomaker_image.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$productCollection = $objectManager->get(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class);
$items = $productCollection->create();
foreach ($items as $_item) {
    try {
        $productRepository = $objectManager->get('Magento\Catalog\Model\ProductRepository');
        $attributeCode = 'incomaker_image';
        $productId = $_item->getId();
        $product = $productRepository->getById($productId);
        $product->setCustomAttribute($attributeCode, $product->getImage());
        $productRepository->save($product);

        $logger->info(__FILE__."::".__LINE__."Save prouct"); 
        $logger->info(print_r([$_item->getId(),$_item->getSku()],true)); 
    } catch (\Exception $e) {
        $logger->info(__FILE__."::".__LINE__); 
        $logger->info(print_r($e->getTraceAsString(),true)); 
    }
}

die(__FILE__."::".__LINE__);