Add Custom Option in Product Programmatically in Magento 2.

Magento 2, Product with custom option used to allow customers to customize the product as per the need from a set of different Custom options.

The custom option is a native feature of Magento and you can add the Custom option by Admin side in product Section.

You can add multiple types of custom option like Text field, Text area, Dropdown, Checkbox, Radio button, File(Image), Multiple Select, Date, Date & Time, Time.

If you want to add custom option programmatically to Product you need to use below code in your module.

<?php
namespace Rbj\CustomOption\Block;

class CustomOption extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Catalog\Model\Product\Option $optionFactory,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        $this->optionFactory = $optionFactory;
        parent::__construct($context,$data);
    }

    /**
    * @param string $sku
    */
    public function addCustomOption($sku)
    {
        try {
            $_product = $this->productRepository->get($sku);
        } catch (\Exception $exception) {
            throw new \Magento\Framework\Exception\NoSuchEntityException(__('Such product doesn\'t exist'));
        }
        $optionsArray = [
            [
                'title' => 'Select option',
                'type' => 'drop_down',
                'is_require' => 1,
                'sort_order' => 1,
                'values' => [
                    [
                        'title' => 'Option 1',
                        'price' => 10,
                        'price_type' => 'fixed',
                        'sku' => 'Option 1 sku',
                        'sort_order' => 1,
                    ],
                    [
                        'title' => 'Option 2',
                        'price' => 10,
                        'price_type' => 'fixed',
                        'sku' => 'Option 2 sku',
                        'sort_order' => 2,
                    ],
                    [
                        'title' => 'Option 3',
                        'price' => 10,
                        'price_type' => 'fixed',
                        'sku' => 'Option 3 sku',
                        'sort_order' => 3,
                    ],
                ],
            ]
        ];

        foreach ($optionsArray as $optionValue) {
            $option = $this->optionFactory
                        ->setProductId($_product->getId())
                        ->setStoreId($_product->getStoreId())
                        ->addData($optionValue);
            $option->save();
            $_product->addOption($option);
            // must save product to add options in product
            $this->productRepository->save($_product);
        }
    }

}

From Template file, You need to call Product SKU, which you want to add Custom options,

$sku = “24-MB05”;
$product = $block->addCustomOption($sku);

add Custom Option
add Custom Option

I have taken SKU as 24-MB05 from Magento Sample data.

3 Replies to “Add Custom Option in Product Programmatically in Magento 2.”

  1. Hello,

    It is not working when multiple option available

    Array
    (
    [0] => Array
    (
    [sort_order] => 1
    [title] => Base Color
    [price_type] => fixed
    [price] => 10
    [type] => drop_down
    [is_require] => 1
    [values] => Array
    (
    [0] => Array
    (
    [title] => Red
    [price] => 10
    [price_type] => fixed
    [sku] => #D6E6FF||Base_Red||black.png
    )

    [1] => Array
    (
    [title] => Blue
    [price] => 20
    [price_type] => fixed
    [sku] => #FF59B9||Base_Blue||blue.png
    )

    [2] => Array
    (
    [title] => Gold
    [price] => 30
    [price_type] => fixed
    [sku] => #9CF9FF||Base_Gold||green.png
    )

    [3] => Array
    (
    [title] => Gray
    [price] => 40
    [price_type] => fixed
    [sku] => #8AFFBC||Base_Gray||red.png
    )

    )

    )

    [1] => Array
    (
    [sort_order] => 2
    [title] => Accent_Color_1
    [price_type] => fixed
    [price] =>
    [type] => drop_down
    [is_require] => 1
    [values] => Array
    (
    [0] => Array
    (
    [title] => Red
    [price] => 10
    [price_type] => fixed
    [sku] => #D9EFFF||Accent_Color_1_Red||black_1.png
    )

    [1] => Array
    (
    [title] => Blue
    [price] => 20
    [price_type] => fixed
    [sku] => #9D5EFF||Accent_Color_1_Blue||blue_1.png
    )

    [2] => Array
    (
    [title] => Gold
    [price] => 30
    [price_type] => fixed
    [sku] => #FFEEB8||Accent_Color_1_Gold||green_1.png
    )

    [3] => Array
    (
    [title] => Gray
    [price] => 40
    [price_type] => fixed
    [sku] => #FFA6E5||Accent_Color_1_Gray||red_1.png
    )

    )

    )

    )

    Please check the array.if one option is available then it is worked great.

    Please check the following screenshot:
    https://www.screencast.com/t/ryI6r1AN3q

    all options add into the single option

Leave a Reply