Add Product Customizable Options Programmatically in Magento 2

Product customizable option in Magento 2 helps to customize the products based on the need with a selection of options like text, file, select and date. For example, the online food delivery store may have options on the product page that allow customers to customize their pizza toppings.

From the admin panel, you can manually add any number of custom options to the products based on your need. But in some cases, you may require to add the product with the customizable option programmatically. For that, you can use this article which helps you to add the product custom option programmatically with simple code.

Here, I am going to give the example with an external script so that I am using Object Manager. You can customize this code based on your need in your custom module by using Dependency Injection (DI) instead of Object Manager.

Initialize Object Manager and Set Area Code

To create an external script, you have to first include the below code in the top of the file. The purpose of the below code is used to access the Magento 2 core functionality from your external file.

use Magento\Framework\App\Bootstrap;

/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;

$bootstrap = Bootstrap::create(BP, $params);

Moving on, use the below script to set the area code as adminhtml,

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);

Add Product Customizable Options

To add the product’s custom option in Magento 2, you need to inject the object of \Magento\Catalog\Api\Data\ProductCustomOptionInterface class in your custom script as follows.

try {
    $productId = 2125;

    $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
   
    $product = $productRepository->getById($productId);

    $options = [
                [
                    'title' => 'Color',
                    'type' => 'drop_down',
                    'is_required' => 1,
                    'sort_order' => 0,
                    'values' => [
                        [
                            'title' => 'Blue',
                            'price' => 5.00,
                            'price_type' => 'fixed',
                            'sku' => 'blue',
                            'sort_order' => 0,
                        ],
                        [
                            'title' => 'Black',
                            'price' => 7.50,
                            'price_type' => 'fixed',
                            'sku' => 'black',
                            'sort_order' => 0,
                        ]
                    ]
                ],
                [
                    'title' => 'Size',
                    'type' => 'drop_down',
                    'is_required' => 1,
                    'sort_order' => 0,
                    'values' => [
                        [
                            'title' => 'Small',
                            'price' => 0,
                            'price_type' => 'fixed',
                            'sku' => 'small',
                            'sort_order' => 0,
                        ],
                        [
                            'title' => 'Medium',
                            'price' => 0,
                            'price_type' => 'fixed',
                            'sku' => 'medium',
                            'sort_order' => 0,
                        ],
                        [
                            'title' => 'Large',
                            'price' => 0,
                            'price_type' => 'fixed',
                            'sku' => 'large',
                            'sort_order' => 0,
                        ]
                    ]
                ]
            ];
  
    foreach ($options as $arrayOption) {
        $product->setHasOptions(1);
        $product->getResource()->save($product);
        $option = $objectManager->create('\Magento\Catalog\Api\Data\ProductCustomOptionInterface')
                                ->setProductId($product->getId())
                                ->setStoreId($product->getStoreId())
                                ->addData($arrayOption);
  
        $option->save();
        $product->addOption($option);
    }

    echo 'Added custom option to the product with Id '.$product->getId(); 
  
} catch (\Exception $e) {
    echo $e->getMessage();
}

Here,

  • Assign the product id 2125 to the variable $productId.
  • Create product repository using the class \Magento\Catalog\Api\ProductRepositoryInterface.
  • Assign the option values as an array to the variable named $options.
  • Add the custom option to the product using the class \Magento\Catalog\Api\Data\ProductCustomOptionInterface.

Below is the complete code to add the customizable options to the product in Magento 2 programmatically,

<?php
use Magento\Framework\App\Bootstrap;
  
/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';
  
$params = $_SERVER;
  
$bootstrap = Bootstrap::create(BP, $params);
  
$objectManager = $bootstrap->getObjectManager();
  
// Set Area Code
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); // or \Magento\Framework\App\Area::AREA_FRONTEND, depending on your need
  
try {
    $productId = 2125;

    $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
   
    $product = $productRepository->getById($productId);

    $options = [
                [
                    'title' => 'Color',
                    'type' => 'drop_down',
                    'is_required' => 1,
                    'sort_order' => 0,
                    'values' => [
                        [
                            'title' => 'Blue',
                            'price' => 5.00,
                            'price_type' => 'fixed',
                            'sku' => 'blue',
                            'sort_order' => 0,
                        ],
                        [
                            'title' => 'Black',
                            'price' => 7.50,
                            'price_type' => 'fixed',
                            'sku' => 'black',
                            'sort_order' => 0,
                        ]
                    ]
                ],
                [
                    'title' => 'Size',
                    'type' => 'drop_down',
                    'is_required' => 1,
                    'sort_order' => 0,
                    'values' => [
                        [
                            'title' => 'Small',
                            'price' => 0,
                            'price_type' => 'fixed',
                            'sku' => 'small',
                            'sort_order' => 0,
                        ],
                        [
                            'title' => 'Medium',
                            'price' => 0,
                            'price_type' => 'fixed',
                            'sku' => 'medium',
                            'sort_order' => 0,
                        ],
                        [
                            'title' => 'Large',
                            'price' => 0,
                            'price_type' => 'fixed',
                            'sku' => 'large',
                            'sort_order' => 0,
                        ]
                    ]
                ]
            ];
  
    foreach ($options as $arrayOption) {
        $product->setHasOptions(1);
        $product->getResource()->save($product);
        $option = $objectManager->create('\Magento\Catalog\Api\Data\ProductCustomOptionInterface')
                                ->setProductId($product->getId())
                                ->setStoreId($product->getStoreId())
                                ->addData($arrayOption);
  
        $option->save();
        $product->addOption($option);
    }

    echo 'Added custom option to the product with Id '.$product->getId(); 
  
} catch (\Exception $e) {
    echo $e->getMessage();
}

Read Also: Creating Simple Products Programmatically in Magento 2

Hope this helps.

Leave a Reply

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