🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Update Product Attribute Value Programmatically in Magento 2

By Sanjay JethvaUpdated on May 22, 2025 1 min read

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.

Sanjay Jethva Full Image
Article bySanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.