Skip to content

Instantly share code, notes, and snippets.

@collymore
Last active August 10, 2021 14:54
Show Gist options
  • Save collymore/3f2e69bdbd67f39727d5545a90a13800 to your computer and use it in GitHub Desktop.
Save collymore/3f2e69bdbd67f39727d5545a90a13800 to your computer and use it in GitHub Desktop.
Magento 2 add Product Custom options to all enabled products
<?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