Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DOC

Create Custom Option Programmatically in Magento 2

Magento-Code-Snippet-5-1

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:

Customoption-2

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.

Magento2

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


5 comments

  • Hardik Makwana
    • ashutosh srivastava (Moderator)
  • Gaurav Jain
  • Matt Bidas
  • Lucas
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home