Reputation: 80
I have created custom attribute named my_shipping_charge in magento 2 programmatically. I set default value '0' for this attribute. It works fine when I create new product. But what if I want to set this attribute for already created product what should I do.? Please help me to solve this problem.
Upvotes: 1
Views: 3192
Reputation: 1483
For already created products we should have to update manually, if the product collection is larger can run a file in root. In this root file we can load all the product collection and set the custom attribute value for all the products and save it.
custom file in root folder will be like below :
<?php
use \Magento\Framework\App\Bootstrap;
require __DIR__ . "/app/bootstrap.php";
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_collections = $instance ->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
$shippingCharge = "custom value";
foreach ($collections as $product) {
$product->setMyShippingCharge($shippingCharge);
$product->save();
}
?>
$shippingCharge will be the custom value have to update. Run the root file in terminal and reindex. And check from admin panel
Upvotes: 4