I have a question, is there a way to add existing attributes to new product? I have some attributes already created in my admin panel and want to add them programmatically , I guess there should be something like this in Product Factory

$_product->setAttribute("Attribute or value of the attribute");

1 Answer 1


You can use below method to update product attribute value.

$product = $this->productRepository->getById($productId);
$product->setData($attributeCode, $attributeValue2);

Also, if you want $objectManager method to create a script. You can do it by following below code snippet.


use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$obj = $bootstrap->getObjectManager();

// Set the state. You can also set "adminhtml"
$state = $obj->get('Magento\Framework\App\State');

// Get the first product of a collection
$products = $obj->get('Magento\Catalog\Model\ResourceModel\Product\Collection');
foreach ($products as $p) {
    $p->setData($attributeCode, $attributeValue);
    $p->getResource()->saveAttribute($p, $attributeCode);

Hope it helps!!!

  • Thank you! How can I add more than one attribute? can I use this method more than twice? $product->setData($attributeCode, $attributeValue2); Commented Sep 2, 2019 at 20:49
  • Thank you it works even with more than 1 attribute code, $product->setData($attributeCode1, $attributeValue1); $product->setData($attributeCode2, $attributeValue2); works perfectly fine. Greetings! Commented Sep 2, 2019 at 21:04
  • Good to hear... you're welcome...
    – Sumit
    Commented Sep 3, 2019 at 1:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.