
To create custom options in a product programmatically you need to use the following code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productId = 1;
$_product = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface')->getById($productId, true);
$options = [
[
'title' => 'drop_down option',
'type' => 'drop_down',
'is_require' => true,
'sort_order' => 4,
'values' => [
[
'title' => 'drop_down option 1',
'price' => 10,
'price_type' => 'fixed',
'sku' => 'drop_down option 1 sku',
'sort_order' => 1,
],
[
'title' => 'drop_down option 2',
'price' => 20,
'price_type' => 'fixed',
'sku' => 'drop_down option 2 sku',
'sort_order' => 2,
],
],
]
];
foreach ($options as $arrayOption) {
$option = $objectManager->create(\Magento\Catalog\Model\Product\Option::class)
->setProductId($_product->getId())
->setStoreId($_product->getStoreId())
->addData($arrayOption);
$option->save();
$_product->addOption($option);
$objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface')->save($_product);
}
Here,
$options: is an array holds multiple custom options.
Once this code is executed, the custom options of types: field, drop down and multi select are created in your product.
Screenshot:

Thank you for reading this article on Create custom option Programmatically in Magento 2 Services, we hope you liked it.
You can also view our wide range of ready-to-use Magento 2 extensions.
Further for any more queries, please reach out to our team via support ticket.
5 comments
public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory ) {
$this->_product = $productFactory->create();
}
I want to have custom option applied to all products.