We will use the event catalog_product_save_before to create product custom option programmatically in magento2.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_product_save_before">
<observer name="magemonkeys_customoption_add_custom_option" instance="MagemonkeysCustomoptionObserverCatalogProductSaveBeforeObserver"/>
</event>
</config>
In our CatalogProductSaveBeforeObserver class we get the product object. We have to check if the custom option with name “Custom Option” and type field already exists.
If not existed, we have to create an array with the options to be created.
<?php
namespace MagemonkeysCustomoptionObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoCatalogApiDataProductCustomOptionInterface;
use MagentoCatalogModelProductOptionFactory;
class CatalogProductSaveBeforeObserver implements ObserverInterface
{
/**
* @var OptionFactory
*/
protected $productOptionFactory;
/**
* Catalog Product After Save constructor.
* @param OptionFactory $productOptionFactory
*/
public function __construct(
OptionFactory $productOptionFactory
) {
$this->productOptionFactory = $productOptionFactory;
}
/**
* Catalog Product Before Save
*
* @param MagentoFrameworkEventObserver $observer
* @return void
*/
public function execute(MagentoFrameworkEventObserver $observer)
{
$product = $observer->getEvent()->getProduct();
$exist = false;
//check if the custom option exists
foreach ($product->getOptions() as $option) {
if ($option->getGroupByType() == ProductCustomOptionInterface::OPTION_TYPE_FIELD
&& $option->getTitle() == 'Custom Option') {
$exist = true;
}
}
if (!$exist) {
try {
$optionArray = [
'title' => 'Custom Option',
'type' => 'field',
'is_require' => false,
'sort_order' => 1,
'price' => 0,
'price_type' => 'fixed',
'sku' => '',
'max_characters' => 0
];
$option = $this->productOptionFactory->create();
$option->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($optionArray);
$product->addOption($option);
} catch (Exception $e) {
//throw new CouldNotSaveException(__('Something went wrong while saving option.'));
}
}
}
}

