Last active
August 10, 2021 14:54
-
-
Save collymore/3f2e69bdbd67f39727d5545a90a13800 to your computer and use it in GitHub Desktop.
Magento 2 add Product Custom options to all enabled products
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Magento\Framework\App\Bootstrap; | |
require __DIR__ . '/app/bootstrap.php'; | |
$bootstrap = Bootstrap::create(BP, $_SERVER); | |
$objectManager = $bootstrap->getObjectManager(); | |
$state = $objectManager->get('\Magento\Framework\App\State'); | |
$state->setAreaCode('adminhtml'); | |
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection'); | |
$productCollection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED); | |
foreach ($productCollection as $product) { | |
$values = [ | |
[ | |
'title' => 'Certificate of Origin', | |
'price' => 75, | |
'price_type' => "fixed", | |
'sku' => "", | |
'sort_order' => 1, | |
'is_delete' => 0 | |
] | |
]; | |
$options = [ | |
[ | |
"sort_order" => 1, | |
"title" => "Additional Certificate", | |
"price_type" => "fixed", | |
"price" => "", | |
"type" => "checkbox", | |
"values" => $values, | |
"is_require" => 0 | |
] | |
]; | |
foreach ($options as $arrayOption) { | |
$product->setHasOptions(1); | |
$product->getResource()->save($product); | |
$option = $objectManager->create('\Magento\Catalog\Model\Product\Option') | |
->setProductId($product->getId()) | |
->setStoreId($product->getStoreId()) | |
->addData($arrayOption); | |
$option->save(); | |
$product->addOption($option); | |
echo $product->getSku(); | |
echo "---\n"; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment