Creating Simple Products Programmatically in Magento 2

Magento has the great feature for adding the product on the admin side. But in some cases, we may require to create the product programmatically (i.e, using external script). This code snippet will help you to create the simple product in Magento 2 programmatically.

Magento 2 has six different types of products (Simple, Configurable, Grouped, Virtual, Bundle & Downloadable Product). Here we will see how to add simple product in Magento 2 using external script.

Create PHP file (i.e, create_simple_product.php) in your Magento 2 root directory and add the following code,

<?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);
  
$obj = $bootstrap->getObjectManager();
  
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager

$product = $objectManager->create('\Magento\Catalog\Model\Product');
$product->setName('Sample Simple Product'); // name of Product
$product->setSku('product-sku'); // sku of product (It must be unique)
$product->setAttributeSetId(4); // attribute set id
$product->setStatus(1); // status of product (1 => enabled / 0 => disabled)
$product->setWeight(1); // weight of product
$product->setVisibility(4); // visibilty of product (1 => Not visible individually / 2 => catalog / 3 => search / 4 => catalog, search)
$product->setTaxClassId(0); // tax class id
$product->setTypeId('simple'); // type of product (simple / virtual / downloadable / configurable)
$product->setPrice(10); // price of product
$product->setStockData(
    [
        'use_config_manage_stock' => 0,
        'manage_stock' => 1,
        'is_in_stock' => 1,
        'qty' => 1000
    ]
);
$product->save();

Assigning product to the category

$categoryLinkRepository = $objectManager->create('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$categoryLinkRepository->assignProductToCategories($product->getSku(),[11, 12]);

Adding image to product

$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, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();

Adding custom option to product

$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\Model\Product\Option')
                    ->setProductId($product->getId())
                    ->setStoreId($product->getStoreId())
                    ->addData($arrayOption);
    $option->save();
    $product->addOption($option);
}

Hope this helps.

Leave a Reply

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