At first create an observer with event - catalog_product_save_before
In the observer place the below code -
/** Dependency classes **/
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Model\Product\OptionFactory;\
public function __construct(
OptionFactory $productOptionFactory
) {
$this->productOptionFactory = $productOptionFactory;
}
$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.'));
}
}