Creating Simple Products Programmatically in Magento 2

A simple product in Magento is a physical item that you can ship and every single product has its own SKU. It has no selectable variations like sizes, colours, etc. Simple products can be sold individually or can be used in association with grouped, bundle, and configurable products. Example of the simple products is the chandelier, cup, teapot etc.

The main difference between a simple product and a virtual product in Magento 2, the simple product has weight and it can be touched and shipped, whereas the virtual product does not have weight and can’t be touched.

In Magento 2 admin panel, we can create/edit any number of products. But during the development phase or testing the website, we may require to create many numbers of products for a unit test. But creating products on the admin side one by one will take lots of time. This problem can be easily solved by creating a custom script to add products programmatically. In this article, you will learn how to create a simple product in Magento 2 programmatically by a custom script.

Initialize Object Manager And Set Area Code

In order 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);

Create Simple Product

To create a new product in Magento 2, it’s necessary to use the following classes in your custom script.

  • \Magento\Catalog\Api\Data\ProductInterfaceFactory
  • \Magento\Catalog\Api\ProductRepositoryInterface classes

Below is the code that used to create a simple product in Magento 2,

try {
    $productInterfaceFactory = $objectManager->create('Magento\Catalog\Api\Data\ProductInterfaceFactory');
    $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
  
    $product = $productInterfaceFactory->create();
  
    // Get the default attribute set id
    $attributeSetId = $product->getDefaultAttributeSetId();
       
    $sku = $urlKey = 'test-simple-product';
  
    $product->setSku($sku)
            ->setName('My Test Simple Product')
            ->setUrlKey($urlKey)
            ->setAttributeSetId($attributeSetId)
            ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)            
            ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
            ->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
            ->setWeight(1) // Weight of the product
            ->setTaxClassId(0) // Tax class id, 0 = None, 2 = Taxable Goods, etc.            
            ->setPrice(100) // Price of the product
            ->setWebsiteIds([1]) // Assign product to websites
            ->setCategoryIds([11, 12, 13]) // Assign product to categories using category id
            ->setStockData(
                [
                    'use_config_manage_stock' => 0,
                    'manage_stock' => 1,
                    'is_in_stock' => 1,
                    'qty' => 999999
                ]
            );
  
    $product = $productRepository->save($product);
  
    if ($product->getId()) {
        echo "Product Created Successfully";
    }
    
} catch (\Exception $e) {
    echo $e->getMessage();
}

Add Images To Product

Then, use the code below which is used to add the images to the product, Before running this script, the images should be placed in the pub/media/import/ folder.

$filesystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$mediaPath = $mediaDirectory->getAbsolutePath();
$imagePath = $mediaPath .'import/sample.jpg'; // Path of the image
$product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
$product->save();

Add Custom Option To Product

If you want to add the custom option to the product, use the code below. To add product’s custom option in Magento 2, you need to use \Magento\Catalog\Api\Data\ProductCustomOptionInterface class as follows.

$options = [
                [
                    "sort_order"    => 1,
                    "title"         => "Custom Option 1",
                    "price_type"    => "fixed",
                    "price"         => "10",
                    "type"          => "field",
                    "is_require"   => 0
                ],
                [
                    "sort_order"    => 2,
                    "title"         => "Custom Option 2",
                    "price_type"    => "fixed",
                    "price"         => "20",
                    "type"          => "field",
                    "is_require"   => 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);
}

Here is the complete code to create a simple 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 {
    $productInterfaceFactory = $objectManager->create('Magento\Catalog\Api\Data\ProductInterfaceFactory');
    $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
  
    $product = $productInterfaceFactory->create();
  
    // Get the default attribute set id
    $attributeSetId = $product->getDefaultAttributeSetId();
       
    $sku = $urlKey = 'test-simple-product';
  
    $product->setSku($sku)
            ->setName('My Test Simple Product')
            ->setUrlKey($urlKey)
            ->setAttributeSetId($attributeSetId)
            ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)            
            ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
            ->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
            ->setWeight(1) // Weight of the product
            ->setTaxClassId(0) // Tax class id, 0 = None, 2 = Taxable Goods, etc.            
            ->setPrice(100) // Price of the product
            ->setWebsiteIds([1]) // Assign product to websites
            ->setCategoryIds([11, 12, 13]) // Assign product to categories using category id
            ->setStockData(
                [
                    'use_config_manage_stock' => 0,
                    'manage_stock' => 1,
                    'is_in_stock' => 1,
                    'qty' => 999999
                ]
            );
  
    $product = $productRepository->save($product);
  
    if ($product->getId()) {
        echo "Product Created Successfully";
    }
 
    $filesystem = $objectManager->create('\Magento\Framework\Filesystem');
    $mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $mediaPath = $mediaDirectory->getAbsolutePath();
    $imagePath = $mediaPath .'import/sample.jpg'; // Path of the image
    $product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
    $product->save();
 
    $options = [
                    [
                        "sort_order"    => 1,
                        "title"         => "Custom Option 1",
                        "price_type"    => "fixed",
                        "price"         => "10",
                        "type"          => "field",
                        "is_require"   => 0
                    ],
                    [
                        "sort_order"    => 2,
                        "title"         => "Custom Option 2",
                        "price_type"    => "fixed",
                        "price"         => "20",
                        "type"          => "field",
                        "is_require"   => 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);
    }
 
} catch (\Exception $e) {
    echo $e->getMessage();
}

You may also like:

Hope this helps.

Leave a Reply

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