0

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

2

You can use below method to update product attribute value.

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

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

<?php

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');
$state->setAreaCode('frontend');

// 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!!!

3
  • Thank you! How can I add more than one attribute? can I use this method more than twice? $product->setData($attributeCode, $attributeValue2); 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! Sep 2, 2019 at 21:04
  • Good to hear... you're welcome...
    – Sumit
    Sep 3, 2019 at 1:31

Your Answer

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

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