Because all the customers don’t have the same requirements so store owner has to sell the same product with different options from which customer can pick the product according to their requirements. Having powerful CMS like Magento 2 allows the store owner to create, store and proceed your own custom attribute in the database. The attribute is nothing but one kind of the property of a product which can be used for fulfilling customer needs.
Several times it happens that you want thousands of products in your Magento 2 stores and you want to update attribute value of products. At that time, manually updating attribute value takes so much time and efforts. Generally, you have to load product collection and then you have to update all product attribute value by using a loop that takes an extensive amount of time. So we are back with another blog that allows you to update products attribute value in very less time compared to product collection update.
For example, you want to update weight (10gm) attribute for all the products in your Magento 2 stores. At that time you have to create one php script file using the below code in the root folder of your Magento 2 Installation.
<?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('frontend'); try { $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection'); $collection = $productCollection->addAttributeToSelect('*') ->load(); $idArray = []; foreach ($collection as $product){ $idArray[] =$product->getId(); } $value = 10; //amount $productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action'); $productActionObject->updateAttributes($idArray, array('weight' => $value), 0); } catch(\Exception $e) { echo $e->getMessage(); exit; }
That’s it! You have successfully update product attribute value for your Magento 2 store products. If you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends.
And, Let us know if you are facing an issue while implementing this code.
Happy Updating!
hello can we do this through data patch
Yes, you can, but this is not advisable, because you need to do this only one time then use the script like above and run that script.
How to apply different attribute value to each product ?