Magento 2 Product update programmatically

magento 2 Product update programmatically

Sometime we need to Magento 2 product update programmatically, like we want to update metatitle and meta description of the all products using the script.

Create “Myscript.php” file on the root and paste the below code.
Execute from the terminal “php Myscript.php

<?php

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');


$store = 0;
$product_collections = $objectManager ->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
$collections = $collections->addFieldToFilter('visibility', 4);
echo "\n";
echo count($collections);
echo "\n";
foreach ($collections as $product) {
    $id 	= $product->getId(); 
    $product 	= $objectManager->create('Magento\Catalog\Model\Product')->load($id);
    $name   	= $product->getName();

	$customTile = 'Shop '.$product->getName();
	$customDescription = 'Shop the '.$product->getName();
	try{
		$product->setStoreId($store);
		$product->setMetaTitle($customTile);
		$product->setMetaDescription($customDescription);
		$product->save();
		echo '-';
	} catch (\Exception $e) {
		echo "\n";
	    echo "Error Id : " . $productId;
	    echo "\n";
	}
}

Like us on Facebook and Linkedin for more updates.

Related Post Detect Device In JQuery

Back To Top