In this post, we will see How we can Update Products attribute for a large number of products in most optimised way possible. Suppose, you have added a product attribute with attribute code ‘wk_shipping’. You want to set 50 unit to this for a large number of products.
Use the following code to Save attribute value for Products:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $array_product = [1,2,3,4,5]; //product Ids $value = 50; //amount $productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action'); $productActionObject->updateAttributes($array_product, array('wk_shipping' => $value), 0);
The function updateAttributes prototype is as such:
/**
* Update attribute values for entity list per store
*
* @param array $productIds
* @param array $attrData
* @param int $storeId
* @return $this
*/
public function updateAttributes($productIds, $attrData, $storeId);
Please check the below images for reference. The value for the product attribute “wk_shipping” was initially set to $99. After running the above code, the value for the same attribute is updated to the given value, that is, $50 in our case.
Before:
After:
I have tried to make a standalone script that is ready to use. You can improve the code by directly injecting the dependency of this class Magento\Catalog\Model\Product\Action in constructor. Hope, this may be helpful in your journey with Magento 2. For any query, do let me know in the comment below. Thanks 🙂
Be the first to comment.