Add Product Custom Option Programmatically
There will be the case that you do have created a product programmatically, but what if you also need to a add product custom option? Just easy as the creation of the product.
In our example we will create a product custom option on saving the product in Magento admin. For that we will use the event catalog_product_save_before to create an an option and added to the product.
Then in our CatalogProductSaveBeforeObserver class firstly we get the product object and we check if the custom option with name "Custom Option" and type field already exists, so not to create it every time we save the product. If not exist, we create an array with the options of the option to be created. Feel free to change it depending on your needs. About the available option types you can have a look on the interface ProductCustomOptionInterface.
The full example as extension can be found here.
Feel free to share this post and ask your questions in the comments below.
Till next time!