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.

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