Magento 2 – Programmatically Update Product Attributes by SKU for All Store Views

importexportmagento2

I am using below code to update product by sku but that is updating price for english store only , i will price of product to get updated in all store view .
getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('sku', 'A960-CQ');
$collection->addAttributeToSelect('*');
foreach ($collection as $product) 
{
    $product->setData('name', 'test description');
    $product->save();
    echo "Product Updated". " ";
} 

Best Answer

You can used below code to update product attributes for all store Added $ for obj

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeIds = array_keys($storeManager->getStores());
$action = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Action');
$updateAttributes['name'] = "test";
$updateAttributes['price'] = 100;
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('sku', 'A960-CQ');
$collection->addAttributeToSelect('*');
foreach ($collection as $product) 
{
    foreach ($storeIds as $storeId) {
        $action->updateAttributes([$product->getId()], $updateAttributes, $storeId);
    }
}

We can use “updateAttributes” method to update Specific Attribute for product instead update all the data

You can pass multiple attribute that you want to updates detail.As show price and name are pass in an array and updateAttributes will update the name and price of the product

Related Topic