How To

How to add Custom Options to the Product Programmatically in Magento 2

Serving options to customize the product the way customers love is a key success for any business and Magento 2 allows you to do the same by creating multiple custom options from the backend. Generally, these custom options are displayed on the store front-end and allow your customer to customize the product as per the need of a set of different Custom options.

From the backend, you can manually create custom options for the product by navigating the backend product edit page. But every time creating the same custom options for the product may become a cumbersome task for the store owner. That’s the reason we are back with another blog that will help you to automatically create and assign custom options to the newly created product once you are done with setting up and save the product from the backend.

Here is the code to do the same by creating custom extension.
Firstly, we need to create an “events.xml” file at this path and add below code.
app\code\Vendor\Extension\etc

<pre class="lang:default decode:true">
<?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_after">
        <observer name="add_product_custom_options" instance="Vendor\Extension\Observer\Productoptions" />
    </event>
</config>
</pre>

Now, create one more file “Productoptions.php” at this location
app\code\Vendor\Extension\Observer

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Observer;
use Magento\Framework\Event\ObserverInterface;
 
class Productoptions implements ObserverInterface
{
 protected $_options;
 
 public function __construct(
        \Magento\Catalog\Model\Product\Option $options
 ) {
        $this->_options = $options;
 }
 
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
        $product = $observer->getProduct();
    
        $options = [
            '0' => [
                'sort_order' => '1',
                'title' => 'option title',
             'price_type' => 'fixed',
                'price' => '5',
                'type' => 'drop_down',
                'is_require' => '0',
                'values' => [
                    '0' =>[
                     'title' => 'A',
                     'price' => '50',
                     'price_type' => 'fixed',
                     'sku' => 'A',
                     'sort_order' => '0',
                     'is_delete' => '0',
                    ],
 
                    '1' => [
                     'title' => 'B',
                     'price' => '100',
                     'price_type' => 'fixed',
                     'sku' => 'B',
                     'sort_order' => '1',
                     'is_delete' => '0',
                    ],
 
                    '2' => [
                     'title' => 'C',
                     'price' => '150',
                     'price_type' => 'fixed',
                     'sku' => 'C',
                        'sort_order' => '2',
                     'is_delete' => '0',
                    ]
                ]
         ]
     ];
        foreach ($options as $arrayOption) {
            $option = $this->_options
                ->setProductId($product->getId())
                ->setStoreId($product->getStoreId())
                ->addData($arrayOption);
            $option->save();
            $product->addOption($option);
     }
 }
}
</pre>

That’s it! You are free to add one or more custom options to this extension code.

Now onwards, whenever admin will try to save any product from the backend the extension will trigger “catalog_product_save_after” and automatically creates and assign custom options to that particular product.

The extension will work for all Magento 2 product types.

If you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends.

And, Let us know if you are facing an issue while implementing this code.

Happy Coding!

Click to rate this post!
[Total: 14 Average: 4.7]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • Hello,
    in above script you took custom option.
    can you please explain how we can add multiple product option in above observer.
    coz when i am trying to add multiple.. it only adds the last option only.

    Thanks in advanced.

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

1 day ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

7 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

7 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago