How to Update Product Attribute Value Programmatically in Magento 2

Magento 2 CMS has a powerful feature of product attributes. It is a property of a product that describes the product more specifically. For example, price, color, weight, etc.

One can create a product attribute in Magento 2  or use the default attribute of Magento 2.

The admin can update product attributes in bulk in Magento 2 or do it programmatically with the method given here.

Update product attribute value programmatically in Magento 2 when, for instance, there is a price change, offer discounts, change product labels, etc., using the below method.

Steps to Update Product Attribute Value Programmatically in Magento 2

Create Data.php file at Vendor\Extension\Helper and use the below code.

<?php

namespace Vendore\Extension\Helper;

use Magento\Catalog\Model\Product\Action as ProductAction;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;

class Data extends AbstractHelper
{
    protected $messageManager;
    private $productCollection;
    private $productAction;
    private $storeManager;

    public function __construct(
        Context $context,
        CollectionFactory $collection,
        ProductAction $action,
        StoreManagerInterface $storeManager
    )
    {
        $this->productCollection = $collection;
        $this->productAction = $action;
        $this->storeManager = $storeManager;
        parent::__construct($context);
    }

    public function setAttributeData($value)
    {
        try {
            $collection = $this->productCollection->create()->addFieldToFilter('*');
            $storeId = $this->storeManager->getStore()->getId();
            $ids = [];
            $i = 0;
            foreach ($collection as $item) {
                $ids[$i] = $item->getEntityId();
                $i++;
            }
            $this->productAction->updateAttributes($ids, array('attribute_code' => $value), $storeId);

        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }
    }
}

Here, pass the updated value to $value.

That’s all!

Feel free to share the solution with Magento community via social media.

Thank You.

Table of Contents