Magento 2 How To Add Custom Options To The Product

If you want to create or add the custom options for any product like simple, bundle, virtual, downloadable etc. , you can use the following code snippet:


// Creating product object using object manager
$productId = 1;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product->load($productId);

// Adding Custom Options to Product
$options = [
                [
                    "sort_order"    => 1,
                    "title"         => "Custom Option 1",
                    "price_type"    => "fixed",
                    "price"         => "10",
                    "type"          => "field",
                    "is_require"   => 0
                ],
                [
                    "sort_order"    => 2,
                    "title"         => "Custom Option 2",
                    "price_type"    => "fixed",
                    "price"         => "20",
                    "type"          => "field",
                    "is_require"   => 0
                ]
            ];
foreach ($options as $customOption) {
    $product->setHasOptions(1);
    $product->getResource()->save($product);
    $option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
                    ->setProductId($product->getId())
                    ->setStoreId($product->getStoreId())
                    ->addData($customOption);
    $option->save();
    $product->addOption($option);
}

If you want to create an product programmatically, you can use the link to get the code snippet for the same.

Leave a Reply