Hello Guys! 👋

In a previous blog, we create a simple product programmatically here is a link to checkout.

Now, in this blog, we create simple products with custom options with the following snippet of code.

Custom options of products are given to the customer to choose their need.

Magento 2 give different type of options. The following are the type of options given by Magento 2.

  • Text
    • Field
    • Area
  • File
  • Select
    • Drop-down
    • Raddio Buttons
    • Checkbox
    • Multiple Select
  • Date
    • Date
    • Date & Time
    • Time
Step 1 : Create simple-product-custom-options.php in your magento 2 root.
<?php
use Magento\Framework\AppInterface;

try {
    require_once __DIR__ . '/app/bootstrap.php';

} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try{
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

    $objectManager = $bootstrap->getObjectManager();

    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');

    $product = $objectManager->create('\Magento\Catalog\Model\Product');
    $product->setSku('sku-test'); // Sku of product 
    $product->setName('Test Sample Product'); // Here set Product name
    $product->setAttributeSetId(4); // Set attribute set id
    $product->setStatus(1); // Here set status on product enabled = 1 & disabled = 0
    $product->setWeight(10); // Here set weight of product
    $product->setVisibility(4); // set here  visibilty of product
    $product->setTaxClassId(0);
    $product->setTypeId('simple'); // Here set type of product (simple/virtual/downloadable/configurable)
    $product->setPrice(100); 
    $product->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 999999999
        )
    );

    $customOption = $objectManager->create('Magento\Catalog\Api\Data\ProductCustomOptionInterface');

    $customOption->setTitle('Text')
        ->setType('area')
        ->setIsRequire(true)
        ->setSortOrder(1)
        ->setPrice(1.00)
        ->setPriceType('fixed')
        ->setMaxCharacters(50)
        ->setProductSku($product->getSku());

    $customOptions[] = $customOption;
    $product->setOptions($customOptions);

    $product->save();
}
catch(\Exception $e){
    print_r($e->getMessage());
}




Now run simple-product-custom-options.php scripts from your browser.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 10

No votes so far! Be the first to rate this post.