To create custom options in a product programmatically you need to use following code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of Object manager $productId = 50; $product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId); $values = [ [ 'record_id'=>0, 'title'=>'Red', 'price'=>10, 'price_type'=>"fixed", 'sort_order'=>1, 'is_delete'=>0 ], [ 'record_id'=>1, 'title'=>'White', 'price'=>10, 'price_type'=>"fixed", 'sort_order'=>1, 'is_delete'=>0 ], [ 'record_id'=>2, 'title'=>'Black', 'price'=>10, 'price_type'=>"fixed", 'sort_order'=>1, 'is_delete'=>0 ] ]; $options = [ [ "sort_order" => 1, "title" => "Field Option", "price_type" => "fixed", "price" => "", "type" => "field", "is_require" => 0 ],[ "sort_order" => 2, "title" => "Color", "price_type" => "fixed", "price" => "", "type" => "drop_down", "is_require" => 0, "values" => $values ],[ "sort_order" => 3, "title" => "Multiple Option", "price_type" => "fixed", "price" => "", "type" => "multiple", "values" => $values, "is_require" => 0 ] ]; $product->setHasOptions(1); $product->setCanSaveCustomOptions(true); foreach ($options as $arrayOption) { $option = $objectManager->create('\Magento\Catalog\Model\Product\Option') ->setProductId($productId) ->setStoreId($product->getStoreId()) ->addData($arrayOption); $option->save(); $product->addOption($option); }
Here,
$values : is an array holds the values for the select type custom option.
$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:
5 comments
public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory ) {
$this->_product = $productFactory->create();
}
I want to have custom option applied to all products.